Comprehensive Guide to Bottom- Sketches
Unweighted, Weighted, Proofs & Implementations; and VarOpt Sketches of a Recurrence on the Bitcoin Chain
1. Introduction to Bottom- Sketches#
A bottom- sketch (also known as a K-Minimum Values (KMV) sketch or a single-hash MinHash sketch)Edith Cohen and Haim Kaplan. Summarizing data using bottom-k sketches. In Proceedings of the Twenty-Sixth Annual ACM Symposium on Principles of Distributed Computing, PODC '07, pages 225–234. Association for Computing Machinery, 2007. doi: 10.1145/1281100.1281133. URL https://doi.org/10.1145/1281100.1281133; Ziv Bar-Yossef, T. S. Jayram, Ravi Kumar, D. Sivakumar, and Luca Trevisan. Counting Distinct Elements in a Data Stream. In José D. P. Rolim and Salil Vadhan, editors, Randomization and Approximation Techniques in Computer Science: 6th International Workshop, RANDOM 2002, volume 2483 of Lecture Notes in Computer Science, pages 1–10. Springer, 2002. doi: 10.1007/3-540-45726-7_1. URL https://doi.org/10.1007/3-540-45726-7_1; and Andrei Z. Broder. On the resemblance and containment of documents. In Proceedings. Compression and Complexity of SEQUENCES 1997, pages 21–29. IEEE Computer Society, 1997. doi: 10.1109/SEQUEN.1997.666900. URL https://doi.org/10.1109/SEQUEN.1997.666900 is a probabilistic data structure used to summarize massive datasets using fixed, tiny memory footprints. Instead of storing every unique item in a stream, it hashes each item onto the interval and retains only the smallest unique hash values.
From those values alone, one can estimate:
- The total number of distinct elements (cardinality),
- The similarity between two sets (Jaccard similarity), and
- Set operations (unions and intersections) without re-scanning raw data.
1.1 Overview & Construction#
Suppose you have a stream of elements and a uniform random hash function .
- Initialize an empty max-heap of capacity alongside a lookup structure to ignore duplicates.
- Hash each item to get a value .
- Update the sketch:
- If is already in the sketch, ignore it.
- If the sketch has fewer than items, insert .
- If the sketch has items and (the current maximum in the heap), evict and insert .
Because updates only require computing a hash and comparing against , processing each item takes expected time or worst-case time.
1.2 Primary Applications#
1.2.1 Cardinality Estimation (Count-Distinct)#
If distinct items are hashed uniformly into , they divide the interval into sub-intervals of expected length . The -th smallest hash value has expected value:
Inverting this suggests ; the estimator that is exactly unbiased, for (with fewer than items the sketch holds them all and counts them exactly), is:
The relative standard error of this estimate is approximately .The variance is exactly for ; at it is infinite. Inverting is only the heuristic: by Jensen’s inequality the plain overestimates, and what makes exactly unbiased is . Keeping the smallest hash values goes back to Bar-Yossef et al.; the unbiased estimator, its variance and the name KMV are from Beyer et al.Ziv Bar-Yossef, T. S. Jayram, Ravi Kumar, D. Sivakumar, and Luca Trevisan. Counting Distinct Elements in a Data Stream. In José D. P. Rolim and Salil Vadhan, editors, Randomization and Approximation Techniques in Computer Science: 6th International Workshop, RANDOM 2002, volume 2483 of Lecture Notes in Computer Science, pages 1–10. Springer, 2002. doi: 10.1007/3-540-45726-7_1. URL https://doi.org/10.1007/3-540-45726-7_1; and Kevin Beyer, Peter J. Haas, Berthold Reinwald, Yannis Sismanis, and Rainer Gemulla. On synopses for distinct-value estimation under multiset operations. In Proceedings of the 2007 ACM SIGMOD International Conference on Management of Data, SIGMOD '07, pages 199–210. Association for Computing Machinery, 2007. doi: 10.1145/1247480.1247504. URL https://doi.org/10.1145/1247480.1247504 Storing hashes yields an estimate with error regardless of whether or .
The same estimator is exactly unbiased in a finite model as well. If the hash is a uniformly random permutation of a universe of items, with ranks , and is the -th smallest rank of the items as an integer (0-based, so the number of universe items ranked strictly below it), then has , and its variance is slightly below , within 1% for : the finite-population factor is a free gain when the set fills a good part of its universe. Section 10.4 proves the unbiasedness and computes the variance exactly over the law of , writing for the set size and for the universe, and uses it with a smaller universe chosen for each record.
1.2.2 Set Merging (Unions)#
Given sketch and sketch built with the same hash function , the exact bottom- sketch of is:This is why KMV sketches merge exactly, in any order and over any partition of the data: each of the smallest hashes of a union is among the smallest of the part that contains it, so the union’s bottom- lies inside the union of the parts’ sketches.
1.2.3 Jaccard Similarity & Intersections#
The Jaccard similarity is estimated from the bottom- sketch of the union, , by the fraction of its elements present in both and :
Membership is read off exactly: an element of that belongs to has fewer than elements of hashed below it, so it is in . When , is a uniformly random -subset of , the count in the numerator is hypergeometric, and is exactly unbiased, with variance
When both sketches hold their whole sets (each set has at most items), compute exactly from them: the formula above is then still an estimate whenever the union exceeds (§10.5).
The intersection size is then estimated as
consistently but not unbiasedly, and the containment by the elements of that hash at or below the -th hash of (all of when holds the whole of ): the fraction of them found in . That -th element belongs to , so when it is also in it is a sure hit, which biases the fraction up by up to about for a containment (the full amount when is smaller than , none when it is much larger; at most 0.00025 at ). The fraction is undefined when no element of is that small, which is common when is much smaller than .These estimates ask little of the hash function. Thorup shows that with a merely 2-independent the expected relative error of estimating a fraction (here ) from a bottom- sample is , within a constant factor of truly random hashing when . Bottom- estimators of Jaccard and containment from two sketches are treated by Cohen and Kaplan.Mikkel Thorup. Bottom-k and priority sampling, set similarity and subset sums with minimal independence. In Proceedings of the Forty-Fifth Annual ACM Symposium on Theory of Computing, STOC '13, pages 371–380. Association for Computing Machinery, 2013. doi: 10.1145/2488608.2488655. URL https://doi.org/10.1145/2488608.2488655; and Edith Cohen and Haim Kaplan. Summarizing data using bottom-k sketches. In Proceedings of the Twenty-Sixth Annual ACM Symposium on Principles of Distributed Computing, PODC '07, pages 225–234. Association for Computing Machinery, 2007. doi: 10.1145/1281100.1281133. URL https://doi.org/10.1145/1281100.1281133
1.3 Comparison: Bottom- vs. MinHash vs. HyperLogLog#
The two usual alternatives are -hash MinHashAndrei Z. Broder. On the resemblance and containment of documents. In Proceedings. Compression and Complexity of SEQUENCES 1997, pages 21–29. IEEE Computer Society, 1997. doi: 10.1109/SEQUEN.1997.666900. URL https://doi.org/10.1109/SEQUEN.1997.666900 and HyperLogLog:Philippe Flajolet, Éric Fusy, Olivier Gandouet, and Frédéric Meunier. HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm. In 2007 Conference on Analysis of Algorithms (AofA 07), volume AH of DMTCS Proceedings, pages 137–156, 2007. doi: 10.46298/dmtcs.3545. URL https://doi.org/10.46298/dmtcs.3545
| Feature | Bottom- Sketch (KMV) | -Hash MinHash | HyperLogLog (HLL) |
|---|---|---|---|
| Hash Functions per Item | |||
| Update Time Complexity | expected, worst | ||
| Memory Footprint | bits | bits | bits (~5–6 bits/register) |
| Best Use Case | Fast updates + set intersections, Jaccard, & subset sums | Locality-Sensitive Hashing (LSH) | Pure COUNT(DISTINCT) at minimal memory |
Here is the size of the hashed universe, as in §1.2.1, so a hash value takes bits, and is the number of HLL registers (standard error about , §15).
2. Weighted Extension: Priority Sampling & Exponential Scaling#
A weighted bottom- sketch generalizes count-distinct sketching to items with positive weights (e.g., revenue, byte volume, or duration). It samples heavy items with higher probability and yields unbiased Horvitz-ThompsonD. G. Horvitz and D. J. Thompson. A Generalization of Sampling Without Replacement from a Finite Universe. Journal of the American Statistical Association, 47(260):663–685, 1952. doi: 10.1080/01621459.1952.10483446. URL https://doi.org/10.1080/01621459.1952.10483446 estimates for total stream weight and arbitrary subset sums.
2.1 Core Intuition: Virtual Replication#
If an item has integer weight , an unweighted sketch could conceptually split into 100 sub-items , hashing each to and taking the minimum:
Computing hashes directly requires work and fails for continuous non-integer weights. Exponential scaling (§2.2.1) reproduces this minimum exactly in time, up to an increasing transformation: , which is also the law of , and it extends to any real . Priority scaling (§2.2.2) matches it only for small ranks, since ; under priority scaling the probability of holding the minimum is therefore not . This does not affect §3, whose unbiasedness proof uses only each rank’s CDF .
2.2 Mathematical Formulations#
Given uniform random hashes and weights :
2.2.1 Method A: Exponential Scaling (PPSWOR)#
Transform into an exponential variable Edith Cohen and Haim Kaplan. Tighter estimation using bottom k sketches. Proceedings of the VLDB Endowment, 1(1):213–224, 2008. doi: 10.14778/1453856.1453884. URL https://doi.org/10.14778/1453856.1453884; and Bengt Rosén. Asymptotic theory for order sampling. Journal of Statistical Planning and Inference, 62(2):135–158, 1997. doi: 10.1016/S0378-3758(96)00185-1. URL https://doi.org/10.1016/S0378-3758(96)00185-1:
The probability that item achieves the minimum rank among set is strictly proportional to its weight:
2.2.2 Method B: Priority Sampling (Uniform Scaling)#
Scale the uniform float directlyPriority sampling is due to Duffield, Lund and Thorup. The same ranks , keeping the smallest, define Ohlsson’s sequential Poisson sampling, used for the Swedish Consumer Price Index since 1989, whose estimator Ohlsson showed to be asymptotically unbiased; the threshold estimator of §2.3 is exactly unbiased (§3).Nick Duffield, Carsten Lund, and Mikkel Thorup. Priority sampling for estimation of arbitrary subset sums. Journal of the ACM, 54(6), December 2007. doi: 10.1145/1314690.1314696. URL https://doi.org/10.1145/1314690.1314696. Article 32; and Esbjörn Ohlsson. Sequential Poisson Sampling. Journal of Official Statistics, 14(2):149–162, 1998. URL https://www.scb.se/contentassets/ca21efb41fee47d293bbee5bf7be7fb3/sequential-poisson-sampling.pdf:
This avoids logarithmic evaluations while maintaining optimal variance bounds.Optimal in a precise sense: Duffield, Lund and Thorup conjectured, and Szegedy proved, that no unbiased scheme sampling items has a smaller total variance than priority sampling with items.Mario Szegedy. The DLT priority sampling is essentially optimal. In Proceedings of the Thirty-Eighth Annual ACM Symposium on Theory of Computing, STOC '06, pages 150–158. Association for Computing Machinery, 2006. doi: 10.1145/1132516.1132539. URL https://doi.org/10.1145/1132516.1132539
2.3 Horvitz-Thompson Estimator#
Assume (otherwise every item is kept, with ). Let be the -th smallest rank in the sketch. The first items () are retained as active samples, while the -th item sets the threshold .
Under Exponential Scaling (): Inclusion probability: Adjusted weight:
Under Priority Sampling (): Inclusion probability: Adjusted weight:
In both schemes, the threshold-setting item receives an adjusted weight .
2.4 Subset Sum Queries#
Let denote the active sample set of size . For any predicate (e.g.,
region == 'EU'):
2.5 Worked Numerical Example ()#
Consider items evaluated with Priority Sampling ():
| Item | Weight () | Hash () | Rank () | Status () | Adjusted Weight |
|---|---|---|---|---|---|
| A | 1st () | ||||
| B | 3rd () | (Threshold setter: ) | |||
| C | 2nd () | ||||
| D | Evicted () |
- True Total Weight:
- Estimated Total Weight: A note added on 2026-11-13: in this table A and C tie at rank (), so “1st” and “2nd” are a convention, not an order. Nothing else changes: both are among the samples, and the estimates stand. With hashes drawn from a continuous distribution a tie has probability zero.
Heavy item A () retains its exact weight (), whereas light item C () is scaled up to to represent both itself and unsampled light items.
3. Mathematical Proof of Unbiasedness#
3.1 The Leave-One-Out Threshold #
Let be independent continuous random variables with CDFs , and (with fewer items every one is kept, with ). Let be the sorted ranks, and set global threshold .
For any item , define the leave-one-out threshold as the -th smallest rank among all items excluding :
Because ranks are mutually independent, is independent of .Conditioning on the ranks of the other items is Cohen and Kaplan’s rank conditioning, which generalises the derivation Duffield, Lund and Thorup gave for priority sampling to any family of rank distributions.Edith Cohen and Haim Kaplan. Tighter estimation using bottom k sketches. Proceedings of the VLDB Endowment, 1(1):213–224, 2008. doi: 10.14778/1453856.1453884. URL https://doi.org/10.14778/1453856.1453884
3.1.1 Fundamental Equivalence#
- Item is inside the top overall ranks if and only if :
- Whenever holds, inserting shifts the -th overall threshold to match :
3.2 General Unbiasedness Proof#
Define the indicator and the adjusted weight estimator:
Using the equivalences from Section 3.1:
Applying the Law of Total Expectation by conditioning on :
Evaluating the inner expectation with held fixed:
Since is independent of , . Thus:
Taking the outer expectation:
By linearity of expectation, for any subset :
3.3 Instantiating Distributions#
Evaluating for specific rank transformations:
Priority Sampling ():
Exponential Scaling ():
3.4 Why the -th Item acts as a Threshold Setter#
Let be the item at position , so . Then , and the estimator of §3.2 gives by itself: its leave-one-out threshold lies below . Counting the -th item as a sample would mean a sample of size , whose leave-one-out threshold would be the -th smallest of the other ranks, , which a sketch of capacity discards (this is the shifted convention of §6.5). So the -th item serves only as the threshold .
3.5 Pairwise Zero Covariance Property#
For Priority Sampling, Duffield et al.Nick Duffield, Carsten Lund, and Mikkel Thorup. Priority sampling for estimation of arbitrary subset sums. Journal of the ACM, 54(6), December 2007. doi: 10.1145/1314690.1314696. URL https://doi.org/10.1145/1314690.1314696. Article 32 proved that for any two distinct items :
As a result, the variance of a subset sum equals the sum of the individual variances:
4. High-Performance Implementations#
4.1 Systems Optimization Strategies#
- Branch-Light Fast-Path Rejection: Cache in a dedicated field. Over of items in large streams fail and are rejected immediately without touching heap memory, as long as the weights do not trend upward along the stream (equal or i.i.d. weights, or items in random order; see §4.4).
- IEEE-754 Bit-Level Floating Point Generation: Construct uniform
by ORing
z >> 12into the mantissa of double1.0(0x3FF0000000000000), forcing the lowest mantissa bit to 1, and subtracting1.0. 51 hash bits survive, and is an odd multiple of between and : the forced bit is what keeps from being . (The crate’s hash, §7.4, keeps all 52 bits on the midpoint grid instead.) - Preconditions: each
idis offered at most once, with its weight already aggregated per key (a repeatedidis a repeated item), and weights are positive and finite;updatedrops any other weight. - In-Place Heap Replacement: Overwrite root
heap[0]directly and runsift_down(0)instead of executing sequentialpop()andpush()calls.
4.2 Rust Implementation#
use std::cmp::Ordering;
/// A single entry in the Priority Sampling Bottom-k Sketch.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct SketchEntry {
pub rank: f64, // Priority rank r_i = u_i / w_i
pub weight: f64, // True item weight w_i
pub id: u64, // Item identifier
pub payload: u32, // Dimension tag / group ID for subset predicates
}
impl PartialEq for SketchEntry {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
self.rank == other.rank && self.id == other.id
}
}
impl Eq for SketchEntry {}
impl PartialOrd for SketchEntry {
#[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SketchEntry {
#[inline(always)]
fn cmp(&self, other: &Self) -> Ordering {
self.rank
.total_cmp(&other.rank)
.then_with(|| self.id.cmp(&other.id))
}
}
/// SplitMix64's finalizer, applied to the seed once, so that seeds `s` and `s + 1` do not
/// hash `id` and `id + 1` alike.
fn mix_seed(seed: u64) -> u64 {
let mut z = seed.wrapping_add(0x9E3779B97F4A7C15);
z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
z ^ (z >> 31)
}
/// Each `id` is offered at most once, with its weight already aggregated per key: a
/// repeated `id` is a repeated item, and `merge` assumes an `id` in both sketches
/// carries the same weight (so its two copies have equal ranks and sort adjacent).
pub struct PrioritySketch {
k: usize,
seed: u64, // mix_seed(seed): independent seeds give unrelated hashes
threshold: f64, // Cached r_(k) for O(1) fast-path rejection
heap: Vec<SketchEntry>,
}
impl PrioritySketch {
pub fn with_capacity(k: usize, seed: u64) -> Self {
assert!(k >= 2, "Capacity k must be >= 2");
Self {
k,
seed: mix_seed(seed),
threshold: f64::INFINITY,
heap: Vec::with_capacity(k),
}
}
#[inline(always)]
fn hash_to_unit_float(&self, id: u64) -> f64 {
let mut z = (id ^ self.seed).wrapping_add(0x9E3779B97F4A7C15);
z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
z ^= z >> 31;
let bits = 0x3FF0_0000_0000_0000_u64 | (z >> 12) | 1;
f64::from_bits(bits) - 1.0
}
#[inline]
pub fn update(&mut self, id: u64, weight: f64, payload: u32) {
if !(weight > 0.0 && weight.is_finite()) {
return; // also drops NaN, which every comparison would let through
}
let u = self.hash_to_unit_float(id);
let rank = u / weight;
// FAST PATH: Rejects >99% of stream items with a single register comparison
if rank >= self.threshold {
return;
}
let entry = SketchEntry { rank, weight, id, payload };
if self.heap.len() < self.k {
let idx = self.heap.len();
self.heap.push(entry);
self.sift_up(idx);
if self.heap.len() == self.k {
self.threshold = self.heap[0].rank;
}
} else {
self.heap[0] = entry;
self.sift_down(0);
self.threshold = self.heap[0].rank;
}
}
pub fn estimate_subset<F>(&self, mut predicate: F) -> f64
where
F: FnMut(&SketchEntry) -> bool,
{
if self.heap.len() < self.k {
return self.heap.iter().filter(|e| predicate(e)).map(|e| e.weight).sum();
}
let inv_tau = 1.0 / self.heap[0].rank;
let mut sum = 0.0;
for entry in &self.heap[1..] {
if predicate(entry) {
sum += entry.weight.max(inv_tau);
}
}
sum
}
#[inline]
pub fn estimate_total(&self) -> f64 {
self.estimate_subset(|_| true)
}
pub fn merge(&mut self, other: &Self) {
assert_eq!(self.seed, other.seed, "Seeds must match to merge sketches");
let mut combined = Vec::with_capacity(self.heap.len() + other.heap.len());
combined.extend_from_slice(&self.heap);
combined.extend_from_slice(&other.heap);
combined.sort_unstable();
combined.dedup_by_key(|e| e.id);
combined.truncate(self.k);
self.heap.clear();
self.threshold = f64::INFINITY;
for entry in combined {
let idx = self.heap.len();
self.heap.push(entry);
self.sift_up(idx);
}
if self.heap.len() == self.k {
self.threshold = self.heap[0].rank;
}
}
#[inline(always)]
fn sift_up(&mut self, mut idx: usize) {
let item = self.heap[idx];
while idx > 0 {
let parent = (idx - 1) >> 1;
if item <= self.heap[parent] {
break;
}
self.heap[idx] = self.heap[parent];
idx = parent;
}
self.heap[idx] = item;
}
#[inline(always)]
fn sift_down(&mut self, mut idx: usize) {
let len = self.heap.len();
let item = self.heap[idx];
let half = len >> 1;
while idx < half {
let mut child = (idx << 1) + 1;
let right = child + 1;
if right < len && self.heap[right] > self.heap[child] {
child = right;
}
if item >= self.heap[child] {
break;
}
self.heap[idx] = self.heap[child];
idx = child;
}
self.heap[idx] = item;
}
}4.3 C99 Implementation#
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
typedef struct {
double rank; // r_i = u_i / w_i
double weight; // w_i
uint64_t id; // Item key
uint32_t payload; // Subset filter tag
uint32_t _pad; // 32-byte alignment padding
} SketchEntry;
typedef struct {
size_t k;
size_t len;
uint64_t seed;
double threshold; // Cached heap[0].rank
SketchEntry heap[]; // Flexible array member
} PrioritySketch;
/* SplitMix64's finalizer, applied to the seed once in ps_create. */
static inline uint64_t mix_seed(uint64_t seed) {
uint64_t z = seed + 0x9E3779B97F4A7C15ULL;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
return z ^ (z >> 31);
}
/* seed is the mixed seed: ids are offered once each, weights aggregated per key. */
static inline double hash_to_unit_float(uint64_t id, uint64_t seed) {
uint64_t z = (id ^ seed) + 0x9E3779B97F4A7C15ULL;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
z ^= z >> 31;
union { uint64_t u; double d; } conv;
conv.u = 0x3FF0000000000000ULL | (z >> 12) | 1ULL;
return conv.d - 1.0;
}
static inline bool entry_gt(const SketchEntry *a, const SketchEntry *b) {
return (a->rank > b->rank) || (a->rank == b->rank && a->id > b->id);
}
PrioritySketch *ps_create(size_t k, uint64_t seed) {
if (k < 2) return NULL;
PrioritySketch *ps = malloc(sizeof(PrioritySketch) + k * sizeof(SketchEntry));
if (!ps) return NULL;
ps->k = k;
ps->len = 0;
ps->seed = mix_seed(seed);
ps->threshold = INFINITY;
return ps;
}
static inline void sift_up(SketchEntry *restrict heap, size_t idx) {
SketchEntry item = heap[idx];
while (idx > 0) {
size_t parent = (idx - 1) >> 1;
if (!entry_gt(&item, &heap[parent])) break;
heap[idx] = heap[parent];
idx = parent;
}
heap[idx] = item;
}
static inline void sift_down(SketchEntry *restrict heap, size_t len, size_t idx) {
SketchEntry item = heap[idx];
size_t half = len >> 1;
while (idx < half) {
size_t child = (idx << 1) + 1;
size_t right = child + 1;
if (right < len && entry_gt(&heap[right], &heap[child])) {
child = right;
}
if (!entry_gt(&heap[child], &item)) break;
heap[idx] = heap[child];
idx = child;
}
heap[idx] = item;
}
void ps_update(PrioritySketch *restrict ps, uint64_t id, double weight, uint32_t payload) {
if (!(weight > 0.0 && isfinite(weight))) return; /* drops NaN too */
double u = hash_to_unit_float(id, ps->seed);
double rank = u / weight;
if (rank >= ps->threshold) return;
SketchEntry entry = { .rank = rank, .weight = weight, .id = id, .payload = payload };
if (ps->len < ps->k) {
size_t idx = ps->len++;
ps->heap[idx] = entry;
sift_up(ps->heap, idx);
if (ps->len == ps->k) {
ps->threshold = ps->heap[0].rank;
}
} else {
ps->heap[0] = entry;
sift_down(ps->heap, ps->k, 0);
ps->threshold = ps->heap[0].rank;
}
}
typedef bool (*ps_predicate_fn)(const SketchEntry *entry, void *ctx);
double ps_estimate_subset(const PrioritySketch *restrict ps, ps_predicate_fn pred, void *ctx) {
double sum = 0.0;
if (ps->len < ps->k) {
for (size_t i = 0; i < ps->len; ++i) {
if (!pred || pred(&ps->heap[i], ctx)) sum += ps->heap[i].weight;
}
return sum;
}
double inv_tau = 1.0 / ps->heap[0].rank;
for (size_t i = 1; i < ps->k; ++i) {
if (!pred || pred(&ps->heap[i], ctx)) {
double w = ps->heap[i].weight;
sum += (w > inv_tau) ? w : inv_tau;
}
}
return sum;
}4.4 Complexity & Memory Profile#
- Memory Usage: bytes. For , total memory is , fitting inside standard CPU L1 data caches.
- Stream Update Throughput: a few ns per item, dominated by one hash and one division
on the fast rejection path: about 3.2 ns/item for the Rust code above with weights
computed on the fly, and about 4.1 ns/item with weights read from an 800 MB array
(, ,
rustc -O, one core of a 2.2 GHz Xeon Gold 6238R; a benchmark, not a crate command). - Heap Replacements: When the ranks are exchangeable along the stream (equal or i.i.d. weights, or items in random order), item enters with probability , so the expected count is . For items and , fewer than items trigger heap re-sorting. If the weights trend upward along the stream, the ranks trend downward and there are more replacements, up to one per item.
5. Sketching a Recurrence: the Colours of Bitcoin Transactions#
Sections 1–4 sketch a stream: items arrive, each is
seen once, and the sketch summarises the set seen so far. What follows uses the same
ideas for a different job, and was built and measured in the Rust repository
coloring-bt-transactions-rs as a new binary, sketch (src/bin/sketch.rs and the
modules under src/bin/sketch/). Here every sketch is made from other sketches, mixed
with real weights, by a recurrence that runs over the 778,613,440 transaction records of
the 2022 Bitcoin chainSatoshi Nakamoto. Bitcoin: A Peer-to-Peer Electronic Cash System, 2008. URL https://bitcoin.org/bitcoin.pdf. The repository’s main binary,
coloring-bt-transactions (src/main.rs), computes the same colours exactly, and
§5.1–5.4 use it to set out the problem: the rule, the
triangular system it solves, and how far an exact solve gets on the 2022 chain before
memory stops it.
One thing should be said at the start, because the title of this post promises
bottom-. The sketch that won is not literally a bottom- sketch. It is
VarOpt with its light items chosen by systematic sampling in block order: a
threshold sampler, the sibling of the priority sampling of §2 rather than one of its
members. The literal weighted bottom- sketch of §2 was built too (prio below) and
measured beside it; it lost by a factor of 6 to 21 at the same size (§8.4). Section 5.7
says which of what follows is known and which is new. Section 6
proves what each variant guarantees, section 7 shows the code, section 8 the
measurements, and the reasons the threshold sampler wins run through all three.
Section 10 turns to two questions that no sketch of a colour answers: from how many blocks a
transaction descends, and how much two transactions share. Section 13
draws the exact colours where they still fit, over the first million records.
Every result of a run of sketch quoted below can be recomputed from files on disk by a
mode of sketch. Most come from modes that fold nothing and only read what the runs wrote:
sketch summarize turns the outputs of chain and eval into the tables of section 8
(the factor above is the column abs_dmean_over_varopt of its errors.tsv, at
, and ), and sketch summary reads count streams back into the
counts of sections 5.4 and 10. Section 7.10 lists the modes and the runs.
Results of the main binary (§5.1–5.4, §7.3, §7.12,
§13) are crate runs too, but of coloring-bt-transactions, and each is
given with its command line or its flags. Two of its whole-chain runs left their logs on disk
(colors.moments.log, colors.laplace.log), and the exact sizes of its --sets run are
a file on disk; the rest were measured while the main binary was written, and are quoted
from its documentation (the crate’s README.md, RUNNING-2022.md and source comments)
or from its write-up, a description of the main binary that we wrote earlier and have
not published, and each such result says which. What no mode of sketch
computes is labelled where it appears: the prototypes and simulations of the design
phase, runs of the main binary, benchmarks, wall-clock times from /usr/bin/time, and
hand projections.
5.1 Colours#
Number the blocks of the chain , with for 2022. The colour of a transaction is a probability distribution over blocks, written as a polynomial
where is the fraction of ’s value that was minted in block . A coinbase minted in block has . Any other transaction spends inputs with amounts , taken from earlier transactions , and its colour is the amount-weighted mixture of theirs:
(1)with equal shares when the amounts sum to zero. The shares are
nonnegative and sum to one, so by induction every colour is a probability
distribution.Read for one block, or for a set of blocks, this
amount-weighted rule is the haircut taint policy of Möser, Böhme and Breuker, under
which a transaction is devalued in proportion to the tainted value among its inputs,
recursively; a colour carries the haircut taint of every coinbase at once. Anderson et
al. argue for a first-in-first-out rule instead, after the precedent of Clayton’s
case. Tironsakkul et al. compare haircut, poison and first-in-first-out with
last-in-first-out and “taint in, highest out” on two thefts; each policy carries one
number of taint per source, not a distribution over
origins.Malte Möser, Rainer Böhme, and Dominic Breuker. Towards Risk Scoring of Bitcoin Transactions. In Rainer Böhme, Michael Brenner, Tyler Moore, and Matthew Smith, editors, Financial Cryptography and Data Security: FC 2014 Workshops, BITCOIN and WAHC 2014, volume 8438 of Lecture Notes in Computer Science, pages 16–32. Springer, 2014. doi: 10.1007/978-3-662-44774-1_2. URL https://doi.org/10.1007/978-3-662-44774-1_2; Ross Anderson, Ilia Shumailov, Mansoor Ahmed, and Alessandro Rietmann. Bitcoin Redux. Workshop on the Economics of Information Security (WEIS 2018), Innsbruck, June 2018. URL https://www.cl.cam.ac.uk/~rja14/Papers/bitcoin-redux.pdf; and Tin Tironsakkul, Manuel Maarek, Andrea Eross, and Mike Just. Probing the Mystery of Cryptocurrency Theft: An Investigation into Methods for Taint Analysis, 2019. URL https://arxiv.org/abs/1906.05754. arXiv:1906.05754 The records
come in file order and every input spends an earlier record, so the transactions form a
DAG listed in topological order, and (1) is evaluated in one
pass. The repository’s main binary does exactly that with --weighted (the loop in
src/main.rs’s run()):
coloring-bt-transactions all --weighted < finalBCUTXO_2022.scmprints every record’s colour as its terms, block and coefficient; without all it stops
at a default limit of 1,000,001 records. Two facts make that fold checkable.
- Mass. A record’s shares sum to one, and computed in
f64they do so to within on every record of the chain (measured by the crate’s examplematrix --csr, §7.12). Under--statsthe main binary audits the fold and prints the worst drift of a colour’s mass from one.No exact--weightedfold has reached the end of the chain (§5.3), so there is no whole-chain drift of the exact colours to quote. The two whole-chain runs that wrote the exact references below (§5.2) carry the colours inf32band lanes, and their audits report (--bands 1024,colors.moments.log) and (--bands 1,colors.laplace.log); the moments and Laplace values beside the lanes are carried inf64. - Blocks. Which blocks a colour names does not depend on the weights. The terms
--weightedprints, zero coefficients included (src/weighted.rsprunes nothing), are exactly the blocks the unweighted fold computes; only the coefficients differ. The blocks with a positive coefficient are thepossupport of §10.1, which differs from them only through zero-amount inputs andf64underflow.
Give every input weight one and a colour becomes a set of blocks, with union in place
of the sum: the support recurrence (5) of §10.1. That reading is
older; it is what the Scheme program that preceded the crate computed. The main binary
keeps two implementations of it, --rings (circular linked lists, the default) and
--sets (sorted u32 arrays), which share no code and print byte-identical output:
diffing the two is a stronger check of the fast one than any test it could be given
alone.
A colour is read through linear functionals: its mean block and its spread, its CDF (“how much of this is older than block ”) and its Laplace values,
at . Their values for every transaction of the chain are on disk, solved as §5.2 shows, and they are what the sketches are measured against in section 8.
5.2 A triangular solve#
Number the records in file order, and read a colour as the row vector of its coefficients . Matrices are written as bold letters or, like of §10.6, as Greek capitals, and an entry as , row before column ( of §10.6 drops the comma). The share matrix is square, with a row and a column for every record, and holds the share of ’s value spent from record :
It is when spends nothing of , and it is the summed share of Proposition 28 when is the parent of a group. A coinbase’s row is zero, and every other row sums to one. Every input spends an earlier record, so is strictly lower triangular. Let the colour matrix have row equal to , and the coinbase matrix have row equal to when is the coinbase of block (the of §10.6, all its mass on ) and otherwise; is the identity. Row of is , which is (1) with the inputs grouped by parent, so the recurrence for all records at once reads
(2)is unit lower triangular, and the one pass of §5.1 is forward substitution on itJohn R. Gilbert and Tim Peierls. Sparse partial pivoting in time proportional to arithmetic operations. SIAM Journal on Scientific and Statistical Computing, 9(5):862–874, 1988. doi: 10.1137/0909058. URL https://doi.org/10.1137/0909058; and Timothy A. Davis. Direct Methods for Sparse Linear Systems. Fundamentals of Algorithms. Society for Industrial and Applied Mathematics, 2006. doi: 10.1137/1.9780898718881. URL https://doi.org/10.1137/1.9780898718881: row is solved from rows already solved, with the same arithmetic in the same order.The rows are records: 778,613,440 of them, for 778,613,438 distinct transaction ids. The two BIP-30 duplicate coinbases, records 142,783 and 142,841, repeat the ids of earlier coinbases; each is a coinbase row of its own, and an input that names a duplicated id reads the later record (the insert displaces the older colour, §7.5). The chain has 2,044,897,328 inputs, so has at most that many nonzero entries: a parent spent twice by one record adds both shares into one entry. Four things follow from reading it so.
It explains the cost. An entry needs a path of edges from to , and every path extends back to a coinbase, so for , the longest path of Corollary 12, and the inverse is a finite sum,
Its entry is the sum, over all paths from to , of the products of the
shares along them: the of Theorem 9. The inverse
of a sparse triangular matrix fills in along reachability in its graph, and row of
has a block wherever reaches that block’s coinbase through positive
shares: the support of §10.1 (pos). That fill-in, and its sets form below,
are what §5.3 and §5.4 measure. There is nothing to factor and no ordering to choose:
is already triangular, in the order of the chain, and the fill-in
is in the answer, not in a factor that a better ordering could keep sparse.
It names the working set. Forward substitution must keep row until the last row
with has been solved, and the sets form of the Boolean solve
below, which keeps zero-amount inputs, until the last row that spends at all. A stream can bound that
only by “has an unspent output”; the release oracle of §5.3 answers the second question
exactly, and so bounds the first.
It says what can be computed. The solve is linear, so it commutes with every linear map of the colours. For any matrix ,
(3)It is the same forward substitution, with columns on the right instead of
. The memory per live record is numbers, flat in the size of the
colour, and the result is exact for whatever projects onto (in exact arithmetic;
the main binary carries the moments and Laplace values in f64 and the bands in f32
lanes, §5.1). The functionals of §5.1 are such projections: and row of
equal to for the mass and the first two moments, from which the mean
and the spread follow; the column for a cut ;
and , with the values of §5.1, for the
Laplace values; and band indicators for the binned colours. They are the
mean and spread of the main binary’s --moments, its --laplace and its
--bands 1024, and the exact references of section 8 are such solves:
coloring-bt-transactions all --bands 1024 --moments --stats \
--release-oracle lastspend-2022.u32 < finalBCUTXO_2022.scm # colors.moments.zst
coloring-bt-transactions all --bands 1 --laplace --stats \
--release-oracle lastspend-2022.u32 < finalBCUTXO_2022.scm # colors.laplace.zstThe first took 1 h 30 min 48 s at a peak of 37.72 GB, the second 38 min 43 s at
5.08 GB (/usr/bin/time -v, at the end of colors.moments.log and
colors.laplace.log). The binned colours of colors.bands1024.zst came from a third
such run, --bands 1024 under the same release oracle, which read the share matrix of
§7.12 in place of the records: 5 h 00 min 18 s at 37.0 GB resident, by the
write-up (its log was not kept), and 8.67 TiB of text, which zstd took to the 1.52 TiB
of the file on disk.
The L1 sketch of §10.6 is (3) too, with for the
blocks and : Proposition 28 is that equation read
row by row. What is not linear in the colour stays outside. The effective number of
blocks of a colour, , is quadratic, and no projection
gives it: if has fewer than columns, some direction with
changes but not . So the fourth field of a line
of colors.moments.zst, the effective number of blocks, is not one of these solves:
under --bands the main binary reads it off the bands, and nothing here uses it.
The support is the same solve over the Booleans. With “or” and “and” in place of the
sum and the product, and replaced by a matrix, forward substitution yields
the supports: the nonzero pattern of gives (pos), and the adjacency of
the spend graph, an entry wherever spends , zero amounts included, gives of
(5) (sets). The series becomes the
reflexive and transitive closure of that graph. The bottom- selection of
§10.3 is not linear, but it passes through unions,
(Lemma 20), so it can be applied after every union of this solve, as is applied to the real one, and still yields at every record (Theorem 22): that is Cohen’s size estimation for reachability sets.Edith Cohen. Size-estimation framework with applications to transitive closure and reachability. Journal of Computer and System Sciences, 55(3):441–453, 1997. doi: 10.1006/jcss.1997.1534. URL https://doi.org/10.1006/jcss.1997.1534
The sketches of §5.5 are this forward substitution with every solved row replaced by
a randomised reduction of itself (unbiased for varopt and prio, §6.2) before any
later row reads it.
5.3 Why the exact colours do not fit#
The support of is the union of the supports of its parents with a positive share
(every parent but a zero-amount input, §10.1), so colours only grow. How much must be held
is a count, not an extrapolation. The main binary’s driver holds a colour for every
transaction with an unspent output, and a colour-free pass over the file counts them:
92,735,490 at the end of the 2022 chain and 92,753,575 at the peak (quoted from the
crate’s documentation, src/oracle.rs). A budget of 450 GB, a round figure below the
503 GiB (540 GB) of memory of the machine of these runs, over that count is
404 weighted terms of 12 bytes (a u32 block and an f64 coefficient), or 1,213 set
terms of 4. The weighted fold passes that early in the file, as
Table 1 measures on prefixes of it.
sketch: coloring-bt-transactions <records> --weighted --sum --stats < finalBCUTXO_2022.scm. --sum prints one number a line and walks the same terms as the full output. The store holds a colour for every transaction with an unspent output, with no release oracle, so these means differ from those of Table 2 and §5.4. The first three rows are in the crate’s RUNNING-2022.md; the 3M row is from the main binary’s write-up. No log of these runs was kept.| records | mean colour held (blocks) | distinct terms held (×12 B) | resident |
|---|---|---|---|
| 500,000 | 1,087 | 1.8 GB | – |
| 1,000,000 | 4,723 | 15.2 GB | – |
| 1,500,000 | 5,984 | 27.7 GB | 32 GB |
| 3,000,000 | 12,754 | 102.6 GB | 107.75 GiB |
The mean colour grows as , and the store is terms, not overhead:
at 3M records mallinfo2 reports 102.59 GB in use against
GB. Throughput over that span fell from 958,000 records
a second to 760. The growth steepens: the local exponent of the live terms rose over
successive half-million windows (1.48, 1.45, 1.82, 2.28), and fits that honour the rise
put the wall, at the write-up’s budget of 450 GiB, between 4.8M and 8M records, or 8M to
11M with every exact saving the main binary has, under 1.5% of the file in every case (a
hand projection). The 3M-record figures, the 760 records a second, the exponents and the
fits are from the main binary’s write-up; RUNNING-2022.md records the fall to 3,000
records a second by 1.5M records.
The exact colour of every transaction of the 2022 chain cannot be materialised on this machine, under any per-transaction representation, and it is not close. That is the fill-in of (2): is a matrix whose rows, at depth, cover most of the past. Even with every colour frozen at the 12,754 blocks of the 3M-record prefix, a store of the census’s 92,735,490 colours would be 12.9 TiB weighted, 4.3 TiB as sets or 8.0 TiB at a bit per block, and the text of every record’s colour, at about 22 bytes a term, is over 100 TB.
Freeing colours earlier. “Has an unspent output” is the only question a stream can
ask, and the wrong one: what forward substitution needs (§5.2) is whether a later
record of this file reads the colour again. Of the 136 million outputs unspent at the
end of the chain, 51,815,075 are OP_RETURN, unspendable, and none of the file’s
2,044,897,328 inputs touches them (from src/oracle.rs). A file has a future, so the
right question is answered by reading it once first. The main binary’s
examples/lastspend.rs writes, in one pass, the last record that spends each
transaction,
cargo run --release --example lastspend -- lastspend-2022.u32 < finalBCUTXO_2022.scmin 5 min 27 s and 2.9 GiB resident, about the size of the array it fills, a file of
3.11 GB (time and memory from the write-up, which writes “2.9 GB”), and
--release-oracle lastspend-2022.u32 hands it to the fold; it is the file every sketch
run of §7.10 takes with --oracle. The peak of the live colours falls from 92,753,575 to
19,361,261, 4.79 times fewer (from examples/lastspend.rs’s documentation). The two
whole-chain runs of §5.2 agree: their --stats progress lines, every 100,000 records,
peak at 19,346,275 colours held, at record 291.4M. Over the first 400,000 records the
oracle takes --weighted --sum from 947 MB to 258 MB resident and from 5.67 s to 5.26 s,
with byte-identical output under every backend (from the write-up). Since a stale oracle
would free a colour still wanted and quietly give a wrong answer, the file carries a magic
string and a record count, checked before any record is read, and every record is checked
against a bound. One subtlety matters later (§7.12): a record that spends the same
transaction twice must free it on the lowest input index that names it, because the
fold walks its inputs from the last to the first (§7.5), and the lowest index is the one
it reaches last.
Under the oracle the distinct live colours of sketch still peak at about 7.6M
(7,593,630 distinct live sketches at the peak of the production run, peak sketches in
its --stats, §9; distinct, because a record that spends one parent shares that
parent’s sketch, §7.2, so this counts fewer than the 19.4M colours held). Multiplied by hundreds of thousands of blocks, that does not fit in
any memory.
5.4 How far the exact sets reach#
The cheapest exact colour goes further than the weighted one: --sets under the release
oracle, four bytes a block rather than twelve, and only the colours the rest of the file
reads. It was run for the size of every colour, the number of blocks in it, which is the
number of its terms (every coefficient is 1 under --sets):
coloring-bt-transactions all --sets --stats --threads 4 \
--release-oracle lastspend-2022.u32 < finalBCUTXO_2022.scm | countWith --threads 4, four threads format the printed terms while the main thread folds,
byte-identical to a serial run. count is a forty-line C filter outside the crate: it
counts the terms of each line, checks that every coefficient is exactly 1, and prints the
count, which became finalBCUTXO_2022.sets-counts.31187785.txt (194 MB, one count a
line). It is there because the text is long: an earlier --sets run over the first
million records, counted by mawk, spent twelve of its fifteen and a half minutes in
mawk, and by the end of this run a line has over 150,000 terms. A shell loop, also outside the crate, read the
fold’s resident set from /proc every two seconds and would kill it at 480 GiB, or when
the machine had less than 10 GiB available.
The guard fired at 480 GiB, with 14 GiB still available and no swap touched, after 31,187,785 records, 4.0% of the file, in 29 h 14 min. Every term of every line had coefficient 1.
| records | elapsed | rate | live block ids | colours held | mean held | resident |
|---|---|---|---|---|---|---|
| 1,000,000 | 3 min | 3k/s | 1.20G | 184,466 | 6,518 | 8.1 GiB |
| 2,000,000 | 13 min | 1k/s | 3.13G | 347,758 | 9,011 | 15.9 GiB |
| 3,000,000 | 32 min | 579/s | 7.11G | 450,743 | 15,779 | 31.7 GiB |
| 5,000,000 | 1.9 h | 399/s | 10.93G | 547,580 | 19,969 | 47.3 GiB |
| 10,000,000 | 5.8 h | 312/s | 22.16G | 799,460 | 27,722 | 90.0 GiB |
| 15,000,000 | 10.4 h | 297/s | 37.66G | 976,547 | 38,561 | 149.9 GiB |
| 20,000,000 | 15.4 h | 259/s | 58.00G | 1,058,194 | 54,809 | 226.8 GiB |
| 25,000,000 | 21.2 h | 229/s | 78.03G | 1,175,549 | 66,376 | 303.2 GiB |
| 30,000,000 | 27.6 h | 210/s | 115.50G | 1,402,294 | 82,368 | 444.0 GiB |
| 31,100,000 | 29.1 h | 202/s | 123.95G | 1,452,310 | 85,350 | 476.5 GiB |
--sets fold under the release oracle, a run of the main binary: records folded, wall time, rate, block ids in the colours held, colours held, their mean size, and the resident set. From the run’s --stats progress lines and the guard’s readings, as recorded in the main binary’s write-up; that log was not kept. The colours held are also the colored txs column of colors.moments.log, whose run used the same oracle, and agree with it at every row.Where the memory goes. Into block ids, as the weighted fold’s went into terms. A
colour is an Rc<[u32]>, ascending, so 123.95G live ids are 461.8 GiB at four bytes; the
14.7 GiB between that and the resident set is the hash map of the colours held, the
allocator’s slack and the batches in flight to the formatting threads. Nothing is stored
for the coefficients. The growth is in the size of a colour held more than in their
number: between 5M and 31.1M records the colours held rise 2.7 times and their mean size
4.3 times, and the cost of a million records rises with it, 8.5 GiB between 5M and 10M
records, 15 between 15M and 25M, and 28 to 30 from 25M to the end. The rate falls the
same way, from 399 records a second to 202, since a union reads and writes both of its
operands whole and the operands are now hundreds of kilobytes.A first
run, single-threaded and to /dev/null, was stopped by hand at 23,800,000 records after
20.6 h, at a peak of 297.5 GiB. Both runs held the same 77,680,891,395 block ids at that
record, as they must; the one above got there 50 minutes sooner and 4.7 GiB larger, the
cost of the formatting threads and the pipe. These numbers are from the write-up; no log
was kept.
--sets run of §5.4 (main
binary, release oracle, stopped by the memory guard at 480 GiB). (a) Records per size:
one bin per size below 10, then ten log-width bins a decade. (b) The share of records
with at most that many blocks, exactly, one step per distinct size (191,575 of them).
Drawn by figs_exact.py, a script outside the crate, from the histogram of
finalBCUTXO_2022.sets-counts.31187785.txt.What the colours look like. Figure 1 shows two
populations with almost nothing between them. 2,872,504 records, 9.2%, have a colour of
exactly one block, and 15.5% have at most 10,000. Then the cumulative share is flat for
more than two decades, and from about 120,000 blocks it climbs nearly vertically: the
quartiles are 136,609, 174,376 and 206,256 blocks, the mean is 152,823, and the largest
colour has 236,013 blocks. Over the last million of these records the median is about
234,000 (233,620). By the end of the prefix most transactions descend from tens of
thousands of blocks or more, and the ones that do not descend from very few. The first
million records alone look nothing like this: their median is 3 blocks, the mean 8,411,
the largest colour 72,383, and 41% of them have a colour of one block. The large
population is what the chain grows into, and it grows at its own front edge: in the
snapshots taken every three hours during the run, most of the records added since the one
before fell into the top one or two bins, next to the largest colour of the moment (from
the write-up). These statistics are computed from finalBCUTXO_2022.sets-counts.31187785.txt
and finalBCUTXO_2022.sets-counts.1000001.txt by stats_counts.py, a script kept with
the runs’ evidence outside the crate, and sketch reports the two medians as the column
ref_p50 of the summary.tsv it writes when it reads the production count file of
§10.11 beside these sizes:
sketch summary --in colors.kmv1024.counts.zst \
--sets-counts finalBCUTXO_2022.sets-counts.31187785.txt \
--range 0:31187785 --range 30187785:31187785 --out summaryExact sets, with every saving the main binary has, reach 4% of the chain on this machine, and the last million records cost about 30 GiB. That cost is still rising, so twice the memory would, by a hand extrapolation of that rise, buy a few million records more, not a second 31 million. It is not the code that stops the fold but the size of what is asked for, the fill-in of the Boolean form of (2). Section 10.10 carries the count to the end of the chain by the coordinated bottom- of §10.3, exact wherever a support has at most blocks.
5.5 Sketching the recurrence#
So every colour is replaced by a sketch of at most about entries, and the sketches are computed by the same recurrence:
(4)where , the candidate, is the exact mixture of the parents’ sketches, and
is a randomised reduction back to about points, applied only when has more
than points (otherwise ; this holds for varopt and prio, while
coord also applies the threshold inherited from its operands, which can drop terms
even below , §6.6 and §7.8). A coinbase is , exactly. What one
wants from is that be an unbiased estimate of , still a probability
distribution, and accurate on the functionals of §5.1, with an error that does not grow
as the recurrence goes deeper into the chain.
In the matrix form of §5.2, (4) is a randomised forward substitution: each row is solved from the rows already solved and then reduced, before any later row reads it. Write for the noise of the reduction at a record that is not a coinbase, and for a coinbase and wherever no reduction happens; for the matrix whose row is , and (for noise) for the matrix whose row is . Row of is ( for a coinbase), so
The error at every record is a fixed linear image of the noises injected on the way to it. Section 6.3 proves what that implies.
5.6 Why a linear combination of sketches is the crux#
In sections 1–4 a merge is a union, , and
it is exact because an item has the same weight in , in and in . Here
the operation is a linear combination: the child’s weight of block is
, a sum of weights that may each be present in one parent’s
sketch and absent from another’s. And the parents overlap heavily. Counted over records
1.4–1.5M of the chain on the main binary’s exact --weighted merge (quoted from its
documentation, src/weighted.rs, and the message of crate commit d8488bf; no log was
kept), 97% of the terms a merge writes arrive in runs, the one-sided
runs averaging 1,900 blocks and the shared runs 140: colours at depth are near-copies of
a few common ancestors, not independent mixtures.
Three consequences shape everything below.
- A block’s weight in the child is assembled from several parents’ estimates. If a parent’s sketch does not hold the block, its share of that block is simply unknown; §6.6 shows that this alone breaks the exactness of a coordinated (same-hash) merge whose ranks depend on the weights. With ranks that depend on the block alone it does not: a block kept in the child’s sketch is kept in the sketch of every parent whose support contains it, and its weight is assembled exactly (§10.3).
- Each node re-estimates an estimate. For the errors not to compound, each reduction must be unbiased conditionally on its inputs (§6.2), and its randomness must be fresh: independent of the randomness that chose the inputs (§6.5).
- Overlap means the parents’ errors are correlated: they share ancestors. Any argument that needs independent parents fails here; the ones below use linearity and conditional expectations only.
5.7 What is known and what is new#
The tools of sections 6 and 10 are known. What is new is the problem they are put to and a few results that come from putting them together. Here is the line between the two, so that the proofs below are read for what they are. “New” means that a search of the literature at review time found no earlier statement, not that none exists.
Known.
- The solve. The recurrence is forward substitution with a unit lower triangular matrix (§5.2). That the solution of a sparse triangular system fills in along reachability in its graph is the observation behind sparse triangular solvers;John R. Gilbert and Tim Peierls. Sparse partial pivoting in time proportional to arithmetic operations. SIAM Journal on Scientific and Statistical Computing, 9(5):862–874, 1988. doi: 10.1137/0909058. URL https://doi.org/10.1137/0909058; and Timothy A. Davis. Direct Methods for Sparse Linear Systems. Fundamentals of Algorithms. Society for Industrial and Applied Mathematics, 2006. doi: 10.1137/1.9780898718881. URL https://doi.org/10.1137/1.9780898718881 that a linear projection commutes with the solve is linearity.
- The reduction. VarOpt with its lights chosen systematically (Definition 1, Theorem 3) is a classical design of survey sampling (Madow, Chao). It is the VarOpt of Cohen et al. with one of their requirements traded for the block order. In particle filtering it is the optimal resampling of Fearnhead and Clifford. Its bound on every cut, point 5, is the interval property of systematic sampling that Cohen, Cormode and Duffield set beside structure-aware VarOpt.William G. Madow. On the Theory of Systematic Sampling, II. The Annals of Mathematical Statistics, 20(3):333–354, 1949. doi: 10.1214/aoms/1177729988. URL https://doi.org/10.1214/aoms/1177729988; M. T. Chao. A general purpose unequal probability sampling plan. Biometrika, 69(3):653–656, 1982. doi: 10.1093/biomet/69.3.653. URL https://doi.org/10.1093/biomet/69.3.653; Edith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Efficient Stream Sampling for Variance-Optimal Estimation of Subset Sums. SIAM Journal on Computing, 40(5):1402–1431, 2011b. doi: 10.1137/10079817X. URL https://doi.org/10.1137/10079817X; Paul Fearnhead and Peter Clifford. On-line inference for hidden Markov models via particle filters. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 65(4):887–899, 2003. doi: 10.1111/1467-9868.00421. URL https://doi.org/10.1111/1467-9868.00421; and Edith Cohen, Graham Cormode, and Nick Duffield. Structure-aware sampling: flexible and accurate summarization. Proceedings of the VLDB Endowment, 4(11):819–830, 2011a. doi: 10.14778/3402707.3402721. URL https://doi.org/10.14778/3402707.3402721 Corollary 4 is summation by parts.
- Reducing afresh at every step. Replacing every iterate of a linear iteration by an unbiased sparse compression, drawn afresh at each step, is the fast randomised iteration (FRI) of Lim and Weare. One of its compressions, their rule (45), keeps the largest entries, selects the others by one systematic pass with a single uniform, and preserves the total exactly: it is the reduction of Definition 1, except that the lights are not laid out in block order. Greene et al. apply such compressions after every matrix product, and the randomly sparsified Richardson iteration of Weare and Webber does the same with pivotal sampling, which also preserves the total.Lek-Heng Lim and Jonathan Weare. Fast Randomized Iteration: Diffusion Monte Carlo through the Lens of Numerical Linear Algebra. SIAM Review, 59(3):547–587, 2017. doi: 10.1137/15M1040827. URL https://doi.org/10.1137/15M1040827; Samuel M. Greene, Robert J. Webber, Jonathan Weare, and Timothy C. Berkelbach. Beyond Walkers in Stochastic Quantum Chemistry: Reducing Error Using Fast Randomized Iteration. Journal of Chemical Theory and Computation, 15(9):4834–4850, 2019. doi: 10.1021/acs.jctc.9b00422. URL https://doi.org/10.1021/acs.jctc.9b00422; Samuel M. Greene, Robert J. Webber, Timothy C. Berkelbach, and Jonathan Weare. Approximating Matrix Eigenvalues by Subspace Iteration with Repeated Random Sparsification. SIAM Journal on Scientific Computing, 44(5):A3067–A3097, 2022. doi: 10.1137/21M1422513. URL https://doi.org/10.1137/21M1422513; and Jonathan Weare and Robert J. Webber. Randomly Sparsified Richardson Iteration: A Dimension-Independent Sparse Linear Solver, 2023. URL https://arxiv.org/abs/2309.17270. arXiv:2309.17270 What the post adds to them is the setting: a single pass of forward substitution over a DAG, in which every unknown is a probability distribution that is kept and reduced once.
- Unbiasedness and the error decomposition. Theorem 7 is the tower property. Theorem 9 and Corollary 10 split the error into the noise of each reduction, as the error of a particle filter is split into the noise of its resampling steps.Pierre Del Moral. Feynman-Kac Formulae: Genealogical and Interacting Particle Systems with Applications. Probability and Its Applications. Springer, 2004. doi: 10.1007/978-1-4684-9393-1. URL https://doi.org/10.1007/978-1-4684-9393-1 The difference is that the Markov kernels are replaced by the fixed path coefficients of the DAG.
- Order against independence. In one dimension it is known that ordering the particles before a stratified or systematic resampling beats the Monte Carlo rate .Mathieu Gerber and Nicolas Chopin. Sequential quasi Monte Carlo. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 77(3):509–579, 2015. doi: 10.1111/rssb.12104. URL https://doi.org/10.1111/rssb.12104; and Mathieu Gerber, Nicolas Chopin, and Nick Whiteley. Negative association, ordering and convergence of resampling methods. The Annals of Statistics, 47(4):2236–2260, 2019. doi: 10.1214/18-AOS1746. URL https://doi.org/10.1214/18-AOS1746 For a functional of bounded variation, Gerber, Chopin and Whiteley bound the error of ordered resampling by the variation times the Kolmogorov distance between the two distributions, which systematic resampling keeps of order by a discrepancy bound of Niederreiter (their equations (5) and (6)); the one-step Corollary 4 is that argument with the heavy blocks kept. In one dimension the optimal-transport resampling of Li et al. is stratified resampling of the sorted particles.Harald Niederreiter. Random Number Generation and Quasi-Monte Carlo Methods, volume 63 of CBMS-NSF Regional Conference Series in Applied Mathematics. Society for Industrial and Applied Mathematics, 1992. doi: 10.1137/1.9781611970081. URL https://doi.org/10.1137/1.9781611970081; and Yichao Li, Wenshuo Wang, Ke Deng, and Jun S. Liu. Stratification and optimal resampling for sequential Monte Carlo. Biometrika, 109(1):181–194, 2022. doi: 10.1093/biomet/asab004. URL https://doi.org/10.1093/biomet/asab004 Proposition 13 is the textbook variance of Poisson sampling, and Proposition 15 is the unbiasedness of priority sampling passed through Theorem 7.
- The support. Folding bottom- sketches exactly through a graph (Lemma 20, Lemma 21, Theorem 22) is Cohen’s size estimation for reachability sets.Edith Cohen. Size-estimation framework with applications to transitive closure and reachability. Journal of Computer and System Sciences, 55(3):441–453, 1997. doi: 10.1006/jcss.1997.1534. URL https://doi.org/10.1006/jcss.1997.1534 On Bitcoin, the mint centrality of Fiz Pontiveros, Steichen and State counts exactly, for each address, the distinct coinbases it can be traced back to, on a prefix of the chain: the support size, per address and without the sketch.Beltran Borja Fiz Pontiveros, Mathis Steichen, and Radu State. Mint Centrality: A Centrality Measure for the Bitcoin Transaction Graph. In 2019 IEEE International Conference on Blockchain and Cryptocurrency (ICBC). IEEE, May 2019. doi: 10.1109/BLOC.2019.8751401. URL https://doi.org/10.1109/BLOC.2019.8751401 The count estimator of Proposition 25 is the one of inverse sampling without replacement. The Jaccard estimate of Proposition 26 is Broder’s and Beyer et al.’s, and (Lemma 27) is an identity. The Cauchy projection of Proposition 28 is Indyk’s, and it follows the recurrence because a linear sketch commutes with any linear map.
New.
- The problem. The post sketches a linear recurrence of probability distributions over a DAG: the colour of every transaction of the chain, the haircut taint of every coinbase at once. It does so with the compression of FRI, applied once at every node of a one-pass forward substitution with fresh randomness and the lights in block order, and adds sketches of the support and of the L1 distance for the questions that reduction cannot answer (§10.2).
- The rate through the recursion, Corollary 12. Through any DAG of convex mixtures, every functional of bounded variation has a root-mean-square error at most at every node, with . Independent inclusion gives only . Lim and Weare state that their error bound does not carry over to their systematic rule, which they support by experiments only; with the lights in block order and for functionals of bounded variation along it, Corollary 12 is such a bound. Its one-step factor is known (above); what is new is its composition through the DAG. The result is modest, and its proof is elementary once the known pieces are in place. Two things it does not settle are measured instead. The error stays flat with depth (§8.3), an open question (§14). Priority sampling and VarOpt with lights in random order fall at about at depth (§6.4, §8.4).
- The universe of each count, §10.4. Every block of a support is at most , and depends on the chain and not on the permutation, so is a valid universe. That brings a finite-population factor. On the deepest supports of the first 31.2M records it halves the theoretical error of a count that stays exactly unbiased; measured over 16 seeds, the error falls to 57%. Mint centrality counts such supports exactly on a prefix; the sketch, with this universe, counts them for every record of the chain. The result is small but practical.
- Three minor lemmas.
- Lemma 23: ranks that depend on the block alone fold the colour weights of the kept blocks exactly.
- Proposition 19: the harmonic cap of overlapping threshold samples.
- Proposition 29: samplers with ranks , P-MinHash among them, have no merge under sums.
- The measurements.
- On the 2022 chain, VarOpt in block order beats the literal bottom- sketch by 6 to 21 times at the same size.
- Its error is flat in depth over 778M records.
- Every result of a run can be recomputed from files on disk by the crate, or is labelled.
6. Proofs#
Throughout this section a reduction acts on a vector of candidates over a set of blocks, with every , total and . In the recurrence (record mode, §6.2). Hats denote the reduced vector , and for a block the cut at and its estimate are
A word on notation, because some letters change meaning from sections 2–3. There
is a threshold on ranks , small ranks are kept, and a kept item is carried at
. In §6.1–6.5 is a threshold on weights: an item is heavy when
its weight exceeds , and kept lights are carried at weight , so this
plays the part of §2’s . §6.6 returns to §2’s rank convention for coord. Also,
below is a cumulative light mass, not a sketch; counts heavy items, not a
hash; is a total mass and the Wasserstein distance; and the mixing shares are
always (, , , or a bare , ), except in and
in Corollary 4 and its proof, where is the Laplace
parameter of §5.1.
6.1 VarOpt by systematic threshold sampling#
Definition 1. Let solve . Call heavy if and light otherwise; let be the heavy set, , and the lights in block order. Put and for . Draw uniform on , and keep light if and only if . The output is
This is a VarOpt-type scheme (inclusion probabilities proportional to weight up to a threshold, and exactly points; ChaoM. T. Chao. A general purpose unequal probability sampling plan. Biometrika, 69(3):653–656, 1982. doi: 10.1093/biomet/69.3.653. URL https://doi.org/10.1093/biomet/69.3.653; Cohen, Duffield, Kaplan, Lund and ThorupEdith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Stream sampling for variance-optimal estimation of subset sums. In Proceedings of the Twentieth Annual ACM-SIAM Symposium on Discrete Algorithms, SODA '09, pages 1255–1264. Society for Industrial and Applied Mathematics, 2009a. doi: 10.1137/1.9781611973068.136. URL https://doi.org/10.1137/1.9781611973068.136; and Edith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Efficient Stream Sampling for Variance-Optimal Estimation of Subset Sums. SIAM Journal on Computing, 40(5):1402–1431, 2011b. doi: 10.1137/10079817X. URL https://doi.org/10.1137/10079817X), with the lights chosen by one systematic pass along the block axis instead of a sequence of random evictions.One random start along the cumulated sizes is the classical systematic design of survey sampling with unequal probabilities, usually traced to Madow. Particle filters use it as systematic resampling.William G. Madow. On the Theory of Systematic Sampling, II. The Annals of Mathematical Statistics, 20(3):333–354, 1949. doi: 10.1214/aoms/1177729988. URL https://doi.org/10.1214/aoms/1177729988; Genshiro Kitagawa. Monte Carlo filter and smoother for non-Gaussian nonlinear state space models. Journal of Computational and Graphical Statistics, 5(1):1–25, 1996. doi: 10.1080/10618600.1996.10474692. URL https://doi.org/10.1080/10618600.1996.10474692; and James Carpenter, Peter Clifford, and Paul Fearnhead. Improved particle filter for nonlinear problems. IEE Proceedings – Radar, Sonar and Navigation, 146(1):2–7, 1999. doi: 10.1049/ip-rsn:19990255. URL https://doi.org/10.1049/ip-rsn:19990255 Fearnhead and Clifford’s optimal resampling for particle filters works the same way. It solves for the same threshold, keeps the heavies at their weight, resamples the lights at weight by a stratified pass, and is optimal among unbiased resampling schemes for a squared-error loss.Paul Fearnhead and Peter Clifford. On-line inference for hidden Markov models via particle filters. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 65(4):887–899, 2003. doi: 10.1111/1467-9868.00421. URL https://doi.org/10.1111/1467-9868.00421 Systematic selection gives up one property that Cohen et al. include in their definition of VarOpt: no positive covariances between the estimates.Cohen, Cormode and Duffield make the trade explicit for ordered keys: systematic sampling keeps the number of sampled keys in every interval within less than one of its expectation but has positive correlations, while for a VarOpt sample in their sense no bound below two holds on every input.Edith Cohen, Graham Cormode, and Nick Duffield. Structure-aware sampling: flexible and accurate summarization. Proceedings of the VLDB Endowment, 4(11):819–830, 2011a. doi: 10.14778/3402707.3402721. URL https://doi.org/10.14778/3402707.3402721 With four equal lights at and , the kept set is either the first and third or the second and fourth, so the first and third have covariance , and their sum has variance against under independent inclusion. That matters for subset sums that are not intervals of the block axis; it does not matter for the cuts and the bounded-variation functionals read in this post, which Theorem 3(5) bounds directly. The accumulator of the code, which starts at , adds and keeps an item each time it crosses an integer, computes exactly this rule (§7.7).
Lemma 2. The threshold exists and is unique. At most items are heavy, at least one is light, the lights hold exactly of the mass, and .
Proof. Let . It is continuous and nonincreasing, equal to for , strictly decreasing for (at least one term is there), and tends to . So has exactly one solution, and it lies above . At , . If the light sum would be , so there would be no lights and , a contradiction; hence , a light exists, and . Finally , so lies where is strictly decreasing; if we would have . Hence . ■
Theorem 3 (VarOpt by systematic sampling). Under Definition 1:
exactly lights are kept, so the output has exactly points;
block is kept with probability , and when kept: every estimate is a Horvitz–Thompson weight, equal to or to ;
for every ;
for every value of : the mass is preserved exactly;
for every cut ,
where is the number of lights ; hence and , deterministically.
Proof of Theorem 3. (1) Each light adds to , so grows by or at each step, and the number of lights kept is . By Lemma 2, is an integer, and , so this is .
(2) Heavies are always kept. Light is kept if and only if the interval , of length , contains an integer. With uniform, is uniform modulo , and an interval of length with a uniform left end modulo 1 contains an integer with probability . So , and .
(3) For a heavy, . For a light, .
(4) By (1) and Lemma 2,
(5) Heavies contribute the same amount to and . The lights are , with true mass and estimated mass times the number kept,
Since , the difference lies in , and gives the strict bound. ■
Point 4 is why every sketched colour is still a probability distribution: the candidate of a record has mass one, and so has its reduction, for every draw. Point 5 is the property that matters for colours, which are read through their CDF.
Corollary 4. For any function of the block, with variation over ,
with strict inequality when . In particular, for one reduction of a colour (): the KS distance is below ; the mean block moves by less than ; each Laplace value moves by less than ; and the Wasserstein distance is below .
Proof. Let and for , with and by point 4. Summing by parts,
whose absolute value is at most , strictly when because . The mean is ; is monotone with values in , so its variation is below ; KS is ; and
■
Remark 5. Point 5 also explains a number measured in section 8. For a diffuse colour, whose lights
are all tiny against , the fractional parts of the run densely through
, so the largest CDF error over all cuts is close to ,
whose expectation is . The single-shot KS distance of varopt measured
on the exact colours was between and for to , a
little lower at small (§8.8; the column ideal_ks_over_tau of
sketch summarize’s floors_eval.tsv).
The code never sorts to find ; it iterates.
Lemma 6. Start from . Given , let count the items above , be the sum of the others (computed directly, not as minus the heavies) and . Then for every ; and if no item counted in exceeds , then .
Proof. Lower bound. by Lemma 2. Suppose . The items above are above , so they contribute to , and the rest contribute
so . (Also , so the division is defined.)
Monotonicity. Each of the items above exceeds , so
that is . Suppose . The items above are above , so , and is less the items in , each larger than . With , the definition of , this gives
that is .
Stopping. If every item counted in is at most , and the others exceed , then , and by uniqueness.
Termination. Otherwise some item counted in exceeds ; it is at most , so it is counted among the heavies at the next pass, and . Since , the stopping condition holds within passes (in exact arithmetic). ■
6.2 Unbiasedness through the DAG, with fresh randomness#
Let be everything drawn up to and including record , in file order. The shares are fixed numbers: they come from the amounts, not from any sketch.
Theorem 7 (unbiased recursion). Suppose each reduction draws randomness independent of , and is conditionally unbiased: coordinate by coordinate. Then and for every record and block . If, in addition, every reduction preserves mass, every has mass exactly one.
Proof of Theorem 7. is a function of the parents’ sketches, which are -measurable because parents come earlier in the file. So
(and trivially so when no reduction happens). By induction in file order, assuming for every earlier ,
The base case is a coinbase, . Mass: the candidate has mass , and the reduction keeps it. ■
Nothing in the proof asks the parents to be independent. They are not: they share ancestors, and so they share the errors of those ancestors’ reductions. Linearity of expectation does not care. What the proof does need is that the reduction be unbiased given its input, which is why the randomness must be fresh: it must be independent of whatever chose the input. VarOpt satisfies this by Theorem 3(3) with drawn per reduction. Two engineering details keep the proof intact: operands that are the same parent are added before reducing ( exactly), and zero-share operands are skipped, which changes nothing in .
Remark 8. In code, is a hash of the seed and the record index (§7.4), so a run is a deterministic function of its input. The theorem treats the hash values as independent uniforms; that is an idealisation of a good counter-based generator, and the seed-replicate tests of §8.5 are the check that it is harmless.
Record mode against the literal fold. run() folds a record’s inputs pairwise, from
the last to the first. Applied literally to sketches (reduce=step), that is
and for
, with , a reduction after every combine, with a
fresh each. The same tower argument shows it is
unbiased too. The default (reduce=record) merges a record’s operands exactly and
reduces once. Both compute the recurrence (1); they differ
only in how often noise is injected. In step mode a record of inputs is reduced up
to times, and the mass folded early is resampled again at every later step. §6.3
shows that every reduction adds a nonnegative term to the variance, so this is the
expected direction, though not a proof that step mode must lose (its intermediate
reductions have smaller thresholds, ). Measured,
it loses everywhere: 1.24–1.72 times the error of record mode at , with 6.15
times as many reductions (§8.6; step.tsv and cost.tsv of sketch summarize).
6.3 How the error propagates#
Let be the noise injected by the reduction at record ( when the record is not reduced, i.e. has at most blocks; we then set , as the code does, so the sums over below may run over all ancestors).
Theorem 9 (error decomposition). For every record ,
where ranges over and its ancestors, , and for (with when is not or an ancestor of ): the sum, over all paths from to in the DAG, of the product of the shares along the path. The coefficients are deterministic and lie in ; is the fraction of ’s value that flowed through .
Proof of Theorem 9. For a coinbase both sides are . Otherwise
and the induction hypothesis on the parents turns this into
which is the claim with the stated recursion for . The are built from shares only, so they are deterministic, and by induction. ■
Corollary 10. Let be any linear functional of a colour (a cut of the CDF, the mean, a Laplace value). The terms are martingale differences in file order, hence orthogonalDavid Williams. Probability with Martingales. Cambridge University Press, 1991. doi: 10.1017/CBO9780511813658. URL https://doi.org/10.1017/CBO9780511813658, and
Proof. is -measurable and by conditional unbiasedness. For ,
Expand the square; the are constants. (Every term is bounded, by Corollary 4, so the expectations exist.) ■
The same split, of the error into the orthogonal noises of the resampling steps, is the standard analysis of particle filters.Pierre Del Moral. Feynman-Kac Formulae: Genealogical and Interacting Particle Systems with Applications. Probability and Its Applications. Springer, 2004. doi: 10.1007/978-1-4684-9393-1. URL https://doi.org/10.1007/978-1-4684-9393-1 There the noise is carried forward by Markov kernels; here it is carried by the fixed coefficients of the DAG.
As §5.2 noted, the coefficients are no new object: is entry of , and Theorem 9 is, row by row, the identity of §5.5,
The of Corollary 12 below is the squared Euclidean norm of row of .
Proposition 11. For VarOpt in record mode and a cut , let be the fractional part of at the cut in reduction . Conditionally on , the cut error equals with probability and with probability . Hence
Proof. Write with an integer. By Theorem 3(5) the error is , and exactly when , which has probability . Its conditional variance is . Combine with Corollary 10. In record mode every candidate has mass , so by Lemma 2 when is reduced, and otherwise. ■
The same argument gives the rate in through the whole recursion, for every functional of bounded variation.
Corollary 12 (the 1/k rate through the recursion). In record mode, let be a function of the block with variation over all the blocks in order, and . For every record ,
where depends on the DAG and the shares only, not on , and , with the number of edges of the longest path from a coinbase to .
Proof. The variation of over the blocks of one candidate, taken in order, is at most (the triangle inequality merges the steps it skips). So Corollary 4 and give for every reduced record , and for the others. Corollary 10 then gives
The come from the shares alone. For the bound on : , so , and is the probability that a walk from , stepping to parent with probability until it reaches a coinbase, visits (it visits at most once, the graph being acyclic). The sum of these probabilities is the expected number of records the walk visits, at most . ■
What this does and does not bound. The decomposition is exact, and the per-reduction term is tight: one reduction alone has a cut error of order . Corollary 12 turns this into a proved bound at every record, for the mean, every Laplace value and every cut. What it does not give is a constant independent of depth, because is the weak point. Along a chain of near-copies, each record mostly its parent plus a little new value and each reduced, stays close to for many ancestors , and grows linearly with the number of such reductions: the bound by itself only says that the error’s standard deviation is at most of order . It does not explain why the error does not grow with depth. Yet that is what the chain shows: is flat from 100M records to the end, at every from 16 to 1024 (§8.3). Two things in the decomposition make it plausible without proving it. Most records do not reduce at all (a record whose operands are one parent returns that parent’s sketch), so most ancestors contribute . And mixing spreads : the over a generation of ancestors sum to at most one, so when value comes from many ancestors is much smaller than . The measured flatness says that, on this chain, the effective sum
stays bounded.
What the recursion costs can be read against a single reduction. A single-shot sketch of
the exact colour (the “IDEAL” of §8.7) has one term in the sum. On the first 3M records,
where exact colours are available, the recursive sketch’s mean
was 29% to 67% above the single shot’s, for to
, in the stratum of colours with more than 32,768 blocks (the eval3m run of §8.7,
read by sketch summarize into ideal.tsv: metric abs_dmean_L, stratum
fix:>32768, column excess). If both errors had the
same shape, those ratios would correspond to variance ratios of to
: the whole ancestry contributes between about two-thirds of a
single-reduction term and two such terms ( to ) beyond the record’s own.
That reading is an inference from the measurements, not a consequence of the
proposition; it also assumes the record’s own term equals the single shot’s, whereas the
record’s reduction uses the threshold of its candidate , close to but not equal to
that of the exact colour .
6.4 Why the error falls as , not #
For VarOpt by systematic sampling, one reduction has a CDF error below , and is at most (more precisely, ): the error of every functional of Corollary 4 is , deterministically, by Theorem 3(5).
Proposition 13. If instead each light is kept independently with probability and weight (Poisson sampling with Horvitz–Thompson weights), the cut error is unbiased with variance , where is the number of lights . For a diffuse colour, whose lights are all small against , this is about , so the error’s standard deviation is of order .
Proof. Each light contributes an independent term , with Bernoulli(): mean , variance . Sum over the lights up to . ■
Priority sampling (prio) is not Poisson sampling, but its Horvitz–Thompson weights
have zero pairwise covariance (§3.5), and conditionally on the leave-one-out threshold
, the -th largest of the priorities of the other blocks
(§6.5’s convention; it is of §3.1 with shifted by one, and it equals
whenever is kept), its raw weight
has variance . So,
for one reduction with unnormalised weights,
With
this is the same order. That last step, the concentration of
, is argued and not proved here; the measured slope of prio’s errors against
is to (§8.4; sketch summarize’s slopes.tsv, every metric but
TV1024).
The two estimators differ in how the lights are spread. Systematic sampling takes exactly one light per interval of of light mass along the block axis: a stratified sample whose strata are consecutive slices of the colour. Its errors cannot pile up along the axis; at every cut they are bounded by one stratum’s mass. Independent inclusion lets them pile up, as a random walk does. Sequential Monte Carlo knows this gain: ordering the particles before a stratified or systematic resampling beats the rate.Mathieu Gerber and Nicolas Chopin. Sequential quasi Monte Carlo. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 77(3):509–579, 2015. doi: 10.1111/rssb.12104. URL https://doi.org/10.1111/rssb.12104; and Mathieu Gerber, Nicolas Chopin, and Nick Whiteley. Negative association, ordering and convergence of resampling methods. The Annals of Statistics, 47(4):2236–2260, 2019. doi: 10.1214/18-AOS1746. URL https://doi.org/10.1214/18-AOS1746 What Corollary 12 adds is that the gain composes through a DAG of mixtures.
Remark 14. What is proved for the recursion is the rate: Corollary 12 bounds the
root-mean-square error of every bounded-variation functional by ,
because each reduction’s error is at most , a per-reduction variance of
order . Under independent inclusion the per-reduction variance is of order
(Proposition 13), and the same decomposition gives only
. What is not proved is uniformity in depth, since can grow (§6.3).
Measured: local log-log slopes of to for the recursive sketch’s
from to over the whole chain (§8.2),
and, for the single-shot IDEAL on exact colours, for KS, for and
for the largest Laplace error (§8.7), from slopes.tsv and ideal_slopes.tsv
of sketch summarize.
That the difference comes from the systematic pass, and not from the thresholds, was checked in the design phase with a prototype (not the final binary and not a crate run, and on a prefix of the chain): a VarOpt with the same thresholds whose lights were chosen in random order rather than along the block axis, run through the real recursion. On the first 1.1M records its mean over colours wider than went from 1,883 to 70 blocks for to , against 898 to 5.3 for the block-ordered prototype, and on the colours wider than 1024 blocks its log-log slope was , like fresh priority sampling’s , against for the block-ordered one. Streamed deeper, at 10M records its mean-block error was 4,457 and 3,182 blocks at and , against 932 and 479; and in the 10–30M window its median was and , against and . Without the block order, VarOpt behaves like priority sampling: both share the same slope on the shallow 1.1M prefix (about ) and both settle to about at depth ( and across the doubling from to ).
6.5 Priority bottom- on the recursion#
prio is the weighted bottom- sketch of §2 applied at every node: priorities
with fresh uniforms for this reduction, the largest kept,
the -th largest priority, and each kept block carried at
. Priorities are written here, the reciprocals of §2’s ranks
, so the largest priorities are the smallest ranks and is §2’s
. (Section 2 keeps items and uses the -th as the threshold; prio
keeps and uses the -th. They are the same scheme with shifted by one.)
Proposition 15. The raw Horvitz–Thompson weights of prio, never renormalised inside the recursion, are
unbiased at every node: .
Proof. Conditionally on the candidate , the proof of §3.2 applies with the leave-one-out threshold computed from the fresh priorities of the other candidates, which are independent of : . That is the hypothesis of Theorem 7, whose proof uses nothing else. ■
Two things are lost against VarOpt. The mass is no longer preserved: the raw total of a node is a random variable with mean one, and along the DAG it wanders as a martingale (from 0.66 to 1.48 between the 5th and 95th percentiles, in one simulation of the design phase). And what is emitted must be a distribution, so it is normalised, , which is a ratio estimator: consistent, with a bias that vanishes as grows (of order at a single node; its size deep in the recursion, where the raw total wanders, was not analysed), but not unbiased. Example 16 is the one measurement of it.
Example 16. Parent A holds one heavy block of weight and 100 light blocks; parent B holds 300
blocks of equal weight. Each is reduced by prio to , and the child
is reduced again. Over 200,000 replicates the normalised estimate of
the heavy block averaged against the exact
(), while the raw Horvitz–Thompson weight averaged
(). (Measured in a simulation during the design; the test suite therefore
asserts unbiasedness of prio’s raw weights, not of its output.)
Fresh randomness is not optional either. The design phase also tried coordinated priority sampling with Horvitz–Thompson re-estimation, one per block for the whole run, and it diverged: in one prototype the raw mass reached to , and in another its mean distance from 1, , was about . The proof of §3.2 needs the rank to be independent of the threshold and of the weight it is applied to. With shared keys, the blocks present in a node’s input were themselves selected because their was small, so given the input is no longer uniform but biased small. The nominal inclusion probability then understates how likely the block is to be kept again, the Horvitz–Thompson weight over-inflates it, and the inflation compounds multiplicatively along the DAG: a block with a small key is kept and inflated to the threshold, its small key gives it a high priority at the next node, so it is kept and inflated again. (This is the mechanism as we understand it; the divergence itself is what was measured.)
6.6 Coordinated bottom-: exact on disjoint supports, biased under overlap#
Here is again a threshold on ranks, as in §2, not the weight threshold of
§6.1–6.5. coord keeps one key per block for the whole run, ranks a
weight at , and stores exact weights rather than
estimates.One key per item, shared by many weight assignments over the
same items (here, all the colours over the blocks), is the coordinated weighted sampling
of Cohen, Kaplan and Sen.Edith Cohen, Haim Kaplan, and Subhabrata Sen. Coordinated weighted sampling for estimating aggregates over multiple weight assignments. Proceedings of the VLDB Endowment, 2(1):646–657, 2009b. doi: 10.14778/1687627.1687701. URL https://doi.org/10.14778/1687627.1687701 A
threshold sample of a vector at is
; a coord sketch of a colour is meant to
be such a sample, with its stored beside it.
Lemma 17 (disjoint supports). Let and have disjoint supports, with exact threshold samples and , and let with . Put . For every , the threshold sample is obtained from the scaled union
by keeping the entries ranked below . Hence the merge that keeps the candidates ranked below , with the -th smallest candidate rank, returns exactly, with at most entries; and when it returns the bottom- sketch of itself.
Proof. For in the support of , because the supports are disjoint, so the rank of in is . If it is below , then and ; conversely an entry of ranked below after scaling is in , with the exact weight. The same holds for . So every block of ranked below is a candidate, with its true weight and its true rank. If , every block of ranked at or below is a candidate, so is the -th smallest rank of and the output is ’s bottom- sketch. Otherwise and at most candidates rank below it. ■
This is test T5 of the code (§7.13), repeated through nested merges. Overlap breaks it, because a block held by one parent’s sketch and not by the other’s has only a lower bound on its weight: the missing parent’s share is unknown and is taken as zero (the “zero rule”).
The share is missing because coord’s rank depends on the weight, and a
block’s weight in a parent differs from its weight in the child: the block can rank
below the merged sketch’s threshold in the child and outside a parent’s sketch, as
does below. With ranks that depend on the block alone the share is never missing: a
block kept by the child is kept by every parent whose support holds it
(Lemma 21), and the weights of a coordinated merge are then
exact (Lemma 23). What such a sketch gives up is the
weighting itself: it is a uniform sample of the support, which serves the count and the
Jaccard similarity of §10 and not the functionals of §5.1.
Example 18 (overlap). Two blocks with keys ; ; , , , so . In the ranks are : , . In they are : , . The merge sees at and at (each from one parent only), with ranks and ; , so and the sketch is at . The truth: in the ranks are , so and the bottom-1 sketch of is at . The merged sketch matches neither: its weight is a strict lower bound, and its threshold vouches for every block below while , at true rank , is missing.
Proposition 19 (the harmonic cap). Let and be exact threshold samples of and , as in Lemma 17, but without disjointness. A block absent from both sketches has true rank in at least , and .
Proof. A block absent from has or , so either way; likewise . Then , that is . And
■
So, when the operands are exact threshold samples, the harmonic cap (cap=harm) is safe
for the membership of blocks that no operand holds: none of them ranks below it. That
is all it guarantees. It does not repair the weights of blocks that one operand holds
and another misses, so the output need not be a threshold sample of even below the
cap: in Example 18 it does not bind (), and
is lost because its weight was underestimated, not because it was unseen. Nor does
the hypothesis survive the recursion: after the first overlapping merge the operands
carry holes and lower-bound weights, and the guarantee no longer applies. Its price is
that sketches shrink, though not because the cap decays. , by a factor of two
when the operands are alike ( and give
and ); but the shares sum to one, so is at least the
share-weighted harmonic mean of the operands’ thresholds and never falls below the
smallest of them. The shrinkage comes from the candidates whose weights are lower
bounds: their ranks are inflated, sit above the tighter cap and are dropped (in the
design-phase prototype the sketches fell to 45–55% of by 100M records). Measured on
the first 3M records at it changed nothing (KS against for
cap=min on colours above 32,768 blocks, with 2.3% fewer peak entries: the column
measured of sketch summarize’s ideal.tsv and peak_entries of eval’s
cost.tsv, both of eval3m), so the default
stayed cap=min. Neither cap removes the bias of the zero rule, which is why coord
lost: its error is almost all bias (§8.4) and does not fall with .
7. Implementation#
The code below is excerpted from the sketch binary of coloring-bt-transactions-rs,
trimmed (// … marks a cut) but not rewritten. It is about 6,500 lines with its tests
(about 12,700 with the stores of section 10, and about 23,000 at commit adfe031 with the
modes that read the runs’ outputs back, §7.10), adds no dependency, and reuses the
repository’s record parser, release oracle, exact weighted store and Laplace tables
through #[path] modules. Two subsections are about the repository’s main binary,
coloring-bt-transactions, whose exact store, record parser and release oracle sketch
reuses: §7.3, the allocator both binaries declare, and §7.12, the share
matrix of §5.2, which the main binary writes once and reads back.
7.1 Where things are#
| file | what it holds |
|---|---|
sketch.rs | command line, global allocator, dispatch to the modes |
hash.rs | every random draw, as a hash of where it is drawn; the permutation of the blocks and the Cauchy draws of §10 |
algebra.rs | the sketch type, the Algebra trait, operand grouping, the n-way merge |
varopt.rs, prio.rs, coord.rs | the three reductions |
driver.rs | the recurrence, driven exactly as run() drives it |
exact.rs | the exact colour as an Algebra, bit-identical to --weighted, with its sets and pos supports |
feed.rs | one parse broadcast to many stores; reference files read in lock-step |
metrics.rs | mean, spread, Laplace, KS, , TV over 1024 bands; and quantiles |
eval.rs, chain.rs, modes.rs | the modes eval, chain, check, emit, decode |
encode.rs | the binary output format |
kmv.rs | the coordinated bottom- of the support: store, capped merges, estimators, count stream |
l1.rs | the Cauchy projection of the colour: store, scale MLE, weighted Jaccard |
count.rs, pick.rs, pairs.rs | the modes count, pick, pairs |
summarize.rs, summary.rs, select.rs, pairstats.rs, describe.rs | the modes that read other runs’ outputs: summarize, summary, select, pairs-stats, describe |
surface.rs, surface_report.rs | the colour surface of section 12 and its report |
tests.rs | tests through the whole pipeline |
7.2 A sketch in memory#
A sketch is a boxed slice of 8-byte entries in strictly ascending block order, behind an Rc:
/// One term of a sketch: 8 bytes.
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Entry {
pub b: u32,
pub w: f32,
}
/// A sketched colour.
#[derive(Debug)]
pub struct Sketch {
/// Strictly ascending `b`; every `w` positive, finite and normal.
pub entries: Box<[Entry]>,
/// varopt: the light weight of this node's own reduction, or 0. prio: its
/// `tau_q`, or 0. coord: the threshold in this sketch's own scale, `+INF`
/// when exact.
pub tau: f64,
/// A reduction happened here or in an ancestor that had a say. `false`
/// means the sketch *is* the exact colour, up to f32 storage.
pub reduced: bool,
}
pub type Handle = Rc<Sketch>;Weights are f32 in a sketch (relative error per store, far below
anything a -point estimate resolves) and f64 inside a merge or a reduction. A
weight that rounds to zero or to a subnormal is dropped, and every sketch is allocated
at its exact length. On top of the entries an Rc box costs 48 bytes. At a
full sketch is 2,048 bytes of entries, exactly a jemalloc size class, so only the rare
output rounds up. The Rc matters more than the layout: most transactions spend
one parent, or one parent several times, and their colour is the parent’s, so the
record answers the parent’s Rc and costs a reference-count bump.
7.3 The allocator is not a detail#
This subsection is about the main binary, whose exact store sketch reuses. At depth the
exact fold is not merge-bound but malloc-bound. Its allocation pattern, hundreds of
thousands of live blocks of 50 KB to 1 MB freed and reallocated at every merge, is the one
glibc’s allocator handles worst: measured over records 1.4M to 1.5M, a malloc costs
26 µs against 47 ns at the head of the chain, a quarter of the fold’s time (a measurement
of the main binary, recorded in its Cargo.toml and src/main.rs).
Two changes fix it, and they only work together. One is jemalloc as the global
allocator, behind the default feature (--no-default-features gives glibc back). The
other is a merge that writes into a fresh, uninitialised allocation at its upper bound
and then shrinks it to the length the merge turned out to have, instead of zero-filling
a staging buffer and copying out (WeightedSets::intern in src/weighted.rs). The
shrink is a downward realloc, which jemalloc does in place and to size, and glibc does
not.
coloring-bt-transactions 1500000 --weighted --sum < finalBCUTXO_2022.scm, before and after the two changes: wall time and resident set, a benchmark quoted from the message of the crate commit that made them, d8488bf (no log kept).1,500,000 records, --weighted --sum | time | resident |
|---|---|---|
| glibc + staged merge | 257.71 s | 30.61 GiB |
| jemalloc + in-place merge | 148.47 s | 30.48 GiB |
The pair is 1.74 times faster, with 0.4% less memory, and its output is md5-identical to
the previous build’s (checked over 30,000 records in seven modes). At 800,000 records the
same pair is 60.28 s and 9.15 GiB against 38.39 s and 9.59 GiB: 1.57 times faster, but
4.8% more resident, so the memory saving is a property of depth rather than of the
change. Depth is where the wall of §5.3 is.--features mimalloc builds
the other candidate, kept because it was measured: as fast, but 15% to 24% more resident
on the same prefix (Cargo.toml). Setting _RJEM_MALLOC_CONF=thp:always puts jemalloc’s
extents on transparent huge pages; it cut the page faults at 1.5M records by 92%, but the
system time did not fall and the resident set grew 4% (the comment beside the allocator
in src/main.rs).
A global allocator belongs to the binary that declares it, so sketch declares the same
one, as its documentation says, “without this line the binary would silently run on the
system allocator whatever the features say”:
// src/main.rs and src/bin/sketch.rs, the same three lines
#[cfg(feature = "jemalloc")]
#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;sketch --stats prints the allocator it runs on, and the first line of the production
run’s emit.err (§9) is sketch emit: allocator jemalloc. The exact store of
sketch eval is src/weighted.rs through #[path], so it gets the in-place merge too,
and a full sketch is 2,048 bytes, a jemalloc size class
(§7.2). sketch itself was not timed under glibc.
7.4 Randomness#
Every draw is a hash of its coordinates, so a run is a deterministic function of its
input (the same seed over the same records writes the same bytes, which is what lets
check reproduce a chain run from a stored file), and the draws are exactly as
independent as each variant needsThe mixer is the output function of
SplitMix64, which Vigna’s public-domain
splitmix.c presents as a fixed-increment
version of Java 8’s SplittableRandom, the generator of Steele, Lea and
Flood.Guy L. Steele, Doug Lea, and Christine H. Flood. Fast splittable pseudorandom number generators. In Proceedings of the 2014 ACM International Conference on Object Oriented Programming Systems Languages & Applications, pages 453–472. Association for Computing Machinery, 2014. doi: 10.1145/2660193.2660195. URL https://doi.org/10.1145/2660193.2660195:
/// Vigna's SplitMix64 output function. `splitmix64(0) == 0xE220A8397B1DCDAF`.
#[inline]
pub fn splitmix64(x: u64) -> u64 {
let mut z = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
/// A hash as a uniform draw strictly inside `(0, 1)`.
#[inline]
pub fn unit(h: u64) -> f64 {
((h >> 12) as f64 + 0.5) * (1.0 / (1u64 << 52) as f64)
}
/// The hash of the coordinates `(seed, salt, x, y)`.
#[inline]
pub fn h3(seed: u64, salt: u64, x: u64, y: u64) -> u64 {
splitmix64(splitmix64(splitmix64(seed ^ salt) ^ x) ^ y)
}
/// `(rec << 20) | j`, the coordinate of one reduction.
#[inline]
pub fn coordinate(rec: u64, j: u64) -> u64 {
assert!(j <= IDEAL_STEP, "step {} does not fit in the 20 bits kept for it", j);
(rec << 20) | j
}
/// `varopt`'s systematic offset for the reduction at `x`.
#[inline]
pub fn varopt_offset(seed: u64, x: u64) -> f64 {
unit(h3(seed, SALT_VAROPT, x, 0))
}
/// `prio`'s priority draw for block `b` in the reduction at `x`.
#[inline]
pub fn prio_draw(seed: u64, x: u64, b: u32) -> f64 {
unit(h3(seed, SALT_PRIO, x, b as u64))
}
/// `coord`'s coordinated key for block `b`: the same in every sketch of a run.
#[inline]
pub fn coord_key(seed: u64, b: u32) -> f64 {
unit(h3(seed, SALT_COORD, 0, b as u64))
}- Fresh per reduction for
varoptandprio: the coordinate holds the record index and the step inside the record ( in record mode, the 1-based fold step in step mode), so no two reductions of a run share a draw. That is the hypothesis of Theorem 7. The largest step value,IDEAL_STEP, is reserved foreval’s single-shot reduction, so an IDEAL draw is never one the recursion also made. - Coordinated for
coord: the key depends on the block only. It is tabulated once per seed for the chain’s 762,261 blocks and a few past them; a block past the table is hashed on the spot, to the same value. - Strictly inside . The top 52 bits plus a half, over , so the
extremes are and , both exact. The obvious 53-bit form
((h >> 11) + 0.5) / 2^53is wrong: is not anf64and rounds to , which makes the largest draw exactly . Theorem 3(5) needs , andpriodivides by its draw. - Salts keep the three variants’ streams apart at equal seeds.
7.5 The driver#
driver.rs copies the loop of src/main.rs’s run() rather than sharing it (that loop
is welded to the exact store), and keeps everything that decides which colour is
combined with what identical to it: the fold order (inputs from the last to the first,
foldr), the shares (the total summed in input order as an f64, equal shares when it
is zero), when a colour dies, and the BIP-30 duplicate transaction ids (an insert
displaces the older colour, which is released).
let total: f64 = inputs.iter().map(|i| i.amount as f64).sum();
let n = inputs.len() as f64;
let share = |i: &Input| if total > 0.0 { i.amount as f64 / total } else { 1.0 / n };
if let Some(o) = &self.oracle {
o.last_reads(rec, inputs, &mut self.last_reads);
}
debug_assert!(self.ops.is_empty());
for i in (0..inputs.len()).rev() {
let prev = inputs[i].prev_tx_id;
let entry = match self.colors.get_mut(&prev) {
// …
};
let taken = match &self.oracle {
Some(_) => self.last_reads[i],
None => entry.1 <= 1,
};
let s = share(&inputs[i]);
if !taken {
entry.1 = entry.1.saturating_sub(1);
let h = clone_handle(&entry.0);
self.ops.push((h, s));
} else {
let (h, _) = self.colors.remove(&prev).expect("just looked it up");
self.ops.push((h, s));
}
}
let c = self.alg.record(&self.ops, rec);With the release oracle an input moves its parent’s colour out of the map when it is
that colour’s last reader, so the colour is freed as soon as the record that consumed it
is done; without it the unspent-output counts decide, as in run(). The map is keyed by
transaction id with a multiplicative hash: SipHash’s resistance to chosen keys buys
nothing over a file of sequential integers.
7.6 One record: grouping, the n-way merge, one reduction#
fn record_mode(&mut self, ops: &[(Handle, f64)], rec: u64) -> Handle {
self.group(ops);
assert!(!self.groups.is_empty(), "record {} has no operand with a positive share", rec);
if self.groups.len() == 1 {
// sum s_i = 1: the parent's colour is the colour.
return Rc::clone(&ops[self.groups[0].0].0);
}
self.merge_groups(ops);
let reduced_in = self.groups.iter().any(|&(i, _)| ops[i].0.reduced);
// … (coord's per-operand caps)
let out = self.finish(reduced_in, &caps, rec, 0);
// …
}group adds the shares of operands that are the same Rc and skips zero shares.
Skipping them is not cosmetic: the chain has tens of thousands of zero-value inputs
inside records of positive total, and a zero-share parent merged anyway adds up to
zero-weight candidates. That pushes past when the real support is smaller,
forcing a reduction of an exact colour, and in the textbook VarOpt loop it made the
threshold negative.
The candidates are formed by a balanced tree of two-pointer merges, levels for groups, in :
/// `sa . a + sb . b` over ascending entries, into `out` (appended), zeros
/// dropped.
pub fn merge_two(a: &[Entry], sa: f64, b: &[Entry], sb: f64, out: &mut Vec<(u32, f64)>) {
out.reserve(a.len() + b.len());
let (mut i, mut j) = (0, 0);
while i < a.len() && j < b.len() {
let (x, y) = (a[i], b[j]);
let (bk, v) = if x.b < y.b {
i += 1;
(x.b, sa * x.w as f64)
} else if y.b < x.b {
j += 1;
(y.b, sb * y.w as f64)
} else {
i += 1;
j += 1;
(x.b, sa * x.w as f64 + sb * y.w as f64)
};
if v > 0.0 {
out.push((bk, v));
}
}
// … (the two tails)
}A heap-based -way merge has the same bound and was much slower in a benchmark (not a mode of the crate): over the first 6M records at it cost 21 ns a candidate for 3–8 groups and 50 ns above that, against 4.5 ns for a two-pointer pass, because a heap’s sift is a chain of unpredictable branches and the pass is one predictable compare. The tree fixes the summation order, so the result is deterministic. Its scratch vectors are pooled between records and trimmed to 32 MB after a consolidation of thousands of parents.
finish then stores the candidates as they are if there are at most of them (they
are the exact mixture of the parents’ sketches), and otherwise reduces once:
Variant::VarOpt => {
if n <= k {
return Sketch::stored(&self.cand, 0.0, reduced_in);
}
let u = hash::varopt_offset(self.cfg.seed, hash::coordinate(rec, j));
let o = varopt::reduce(&self.cand, k, u, &mut self.vo, &mut self.out);
self.work.reductions += 1;
if o.off_by_one(k) {
self.work.off_by_one += 1;
}
Sketch::stored(&self.out, o.tau, true)
}reduce=step is the same machinery, folding pairwise with
merge_two(&h.entries, *s, &acc.entries, 1.0, …) and calling finish after every
combine with step index .
7.7 The VarOpt reduction#
The threshold comes from Lemma 6: a few linear passes, each summing the lights directly.
pub fn threshold(cand: &[(u32, f64)], k: usize, scratch: &mut Scratch) -> f64 {
let w: f64 = cand.iter().map(|c| c.1).sum();
let mut thr = w / k as f64;
for _ in 0..MAX_PASSES {
let (mut heavy, mut light, mut max_light) = (0usize, 0.0f64, 0.0f64);
for &(_, v) in cand {
if v > thr {
heavy += 1;
} else {
light += v;
max_light = max_light.max(v);
}
}
if heavy >= k {
break; // only rounding can get here; the sort decides
}
let next = light / (k - heavy) as f64;
if max_light <= next {
return next.max(max_light);
}
thr = next;
}
threshold_sorted(cand, k, scratch)
}The textbook loop starts from and subtracts each heavy. On this chain that is wrong
in a way that matters: a merge can have a few items holding nearly all the mass and a
tail of thousands of tiny ones, and minus the heavies is then the cancellation
residue of two nearly equal numbers. It came out negative in half of the trials of a
simulation run during the design, which made every candidate heavy. One to three passes
is the rule, and by Lemma 6 the loop never needs more than
passes. Geometrically decaying weights (ratio ), the shape near-copy chains
make, are the slow case. Pass lowers the threshold by a factor of about
, which starts near and falls towards 1 as nears
, and each pass adds only about
heavies. With , that is 16
passes; with , it is 32. After MAX_PASSES the code falls
back to threshold_sorted, which partially sorts the top (only they can be
heavy, since ) and builds the tail sums from the small end, again without
differences. The result is clamped to at least the largest light weight, which only
rounding can violate and which keeps every .
The sample itself is one pass:
let (mut heavies, mut lights) = (0, 0);
// The accumulator is kept in [0, 1): subtracting the crossing rather than
// comparing floors keeps its absolute precision at the scale of one item,
// however many items the pass walks.
let mut acc = u;
// A multiply rather than a divide per item; v * (1/tau) and v / tau differ
// by at most an ulp, which moves an inclusion probability by 1e-16.
let inv = 1.0 / tau;
for &(b, v) in cand {
if v > tau {
out.push((b, v));
heavies += 1;
continue;
}
acc += v * inv;
if acc >= 1.0 {
out.push((b, tau));
lights += 1;
acc -= 1.0;
}
}In exact arithmetic it keeps exactly points (Theorem 3(1));
in floating point the last crossing can land on either side of an integer, giving
. The output is never trimmed back to , because trimming would bias it; such
events are only counted (k+-1 in --stats), and the code asserts at most
points. Over the whole chain at and the count was zero (the column
off_by_one of pass B’s cost.tsv, and k+-1 0 in the production run’s --stats).
7.8 prio and coord#
prio keeps the largest priorities and carries each kept block at :
// …
q.extend(
cand.iter()
.enumerate()
.map(|(i, &(b, v))| (v / prio_draw(seed, x, b), i as u32)),
);
// Descending by priority: the k largest land in q[..k], the (k+1)-th at k.
q.select_nth_unstable_by(k, |a, b| b.0.total_cmp(&a.0));
let tau = q[k].0;
// …
for &i in keep.iter() {
let (b, v) = cand[i as usize];
out.push((b, v.max(tau)));
}prio’s weights stay raw Horvitz–Thompson inside the recursion
(Proposition 15) and are normalised only when emitted. coord
merges by Lemma 17: each operand’s (rank) threshold, rescaled
to the merged colour, caps the new one.
pub fn cap_of(groups: impl Iterator<Item = (f64, f64)>, mode: Cap) -> f64 {
match mode {
Cap::Min => groups
.filter(|g| g.1.is_finite())
.map(|(s, tau)| tau / s)
.fold(f64::INFINITY, f64::min),
Cap::Harm => {
let inv: f64 = groups.filter(|g| g.1.is_finite()).map(|(s, tau)| s / tau).sum();
if inv > 0.0 {
1.0 / inv
} else {
f64::INFINITY
}
}
}
}Unlike the other two, coord runs its reduction on every record with several operands,
not only when there are more than candidates: a cap inherited from reduced operands
can drop candidates even when there are fewer than , and the result then carries a
finite threshold. Its reduction keeps the candidates ranked strictly below
(with when there are at most
candidates), and its estimate lifts each kept weight to before
normalising, which is mandatory there because the zero rule leaves the raw total below
one. Every variant emits the same way:
fn emit(&self, c: &Handle, out: &mut Vec<(u32, f64)>) {
out.clear();
let finite_coord = self.cfg.variant == Variant::Coord && c.tau.is_finite();
let lift = if finite_coord { 1.0 / c.tau } else { 0.0 };
let mut total = 0.0;
for e in c.entries.iter() {
let w = (e.w as f64).max(lift);
total += w;
out.push((e.b, w));
}
if total > 0.0 {
for x in out.iter_mut() {
x.1 /= total;
}
}
}For varopt the normalisation is the identity up to f32 rounding whenever the
reduction keeps points (Theorem 3(1), (4)); on the synthetic
DAG of §7.13 (where no event occurs) mass_raw stays within of .
In a event (§7.7) one light more or one fewer is kept at weight , the
raw mass is , and emit genuinely rescales the sketch and records
raw_mass - 1 (§7.11); no such event occurred on the chain.
7.9 Numerical care, in one place#
- Sums in
f64, storage inf32; zero and subnormal weights dropped at storage. - No light mass obtained as a difference, in either threshold routine.
- clamped to at least the largest light; a (heavies holding everything) returns the heavies.
- The systematic accumulator kept in by subtracting each crossing, so its absolute precision is that of one item whatever the length of the pass.
- Draws strictly inside .
- outputs counted, never trimmed.
7.10 Modes, threads and the commands that were run#
evalruns the exact store (exact.rs, bit-identical to--weighted) on its own thread beside one thread per sketch configuration, all fed by one parse, and measures every sketch against the whole exact colour every--everyrecords, next to the same variant’s single-shot reduction of the exact colour (the IDEAL). The exact store’s memory caps it at a prefix: 3M records without--force-exact.chainruns the whole chain, one store thread per configuration, and compares each sampled record’s estimate with the exact Laplace values, moments and (optionally) 1024-band binned colours on disk.--every 16samples every 16th record into the per-bucket summaries (buckets.tsv);--rows-every 16also writes every 16th of those sampled records, so every 256th record of the chain, to the per-record row filesrows.<config>.tsv. Reference threads runzstd -dcon those files and cut them into batches on the same boundaries as the records (8,192 records a batch), checking every line’s transaction id. The bounded channels (8 batches) keep the fastest store from running away from the slowest. Errors are aggregated per 10M-record bucket, over all rows and over reduced rows (a reduction somewhere in the ancestry).emitwrites every record’s estimate: a reader thread parses, the store thread folds, an encoder thread writes, so parsing, sketching and the pipe tozstdoverlap.checkrecomputeschain’s metric columns from anemitfile, byte for byte, so a stored production file can be validated after the fact;decodeturns the binary format into text.
The modes added since (commits 159874d to adfe031) fold nothing. They read files that the runs wrote and compute from them the numbers the post states, and each was checked against the script or ad-hoc program it replaces; their commands are given where their results are.
summarizereads whatchainandevalwrote and computes the tables of section 8: error against and against depth, slopes, bias across seeds, step against record mode, the recursion against one reduction and, with--moments, the floors. It follows the conventions of the Python analysis it replaces, whose means and quantiles of the reduced rows it matches to relative.summaryreads count streams back into what a whole-chain count is judged by: exactness, quantiles per bucket and per--range, the seeds against each other, and the exact sizes where they exist (§5.4, §10.10, §10.11). Every cell of themawkand Python passes it replaces comes out equal, except one p90 that Python printed rounded (54 for 53.5).select prefix|chainchooses the records worth comparing from a count stream and writes the filepick --selectreads, byte-identical to the Pythonselect.py’s.pairs-statsreduces one or morepairsoutputs to the bias, variance, agreement and quantile tables of §10.9 and §10.10, pooling the seeds of runs over the same rows, and computes the other similarities of §10.7 (from commit adfe031).describesays what each production sketch cut out bydecode --selectis and compares it with its exact colour binned in 1024 bands (section 11). Beside it,pick --bands-refcopies those binned colours during a fold, andpairs --bandsadds the binned TV of every pair.surfaceaverages the production sketches, or the binned exact colours, into the matrices of section 12, bit-identical on prefixes to the two programs first used, andsurface-reportturns them into that section’s tables and checks.
Both binaries run on jemalloc (§7.3).
cargo build --release --bin sketch
cargo test --release --bin sketch -- --include-ignored
# eval3m: the first 3M records, exact colours side by side (abridged: 26 configs in one pass)
sketch eval --config varopt:16 … --config varopt:4096 \
--config varopt:64:seed=2 … --config varopt:64:reduce=step --config varopt:256:reduce=step \
--config prio:16 … --config prio:1024 --config coord:16 … --config coord:1024 --config coord:64:cap=harm \
--oracle lastspend-2022.u32 --out eval3m --limit 3000000 --every 200 \
--check-ref --laplace-ref colors.laplace.zst --stats < finalBCUTXO_2022.scm
# pass A: the whole chain, k <= 256, baselines, seeds, step mode, with the binned reference
sketch chain --config varopt:16 --config varopt:32 --config varopt:64 --config varopt:128 --config varopt:256 \
--config varopt:64:seed=2 --config varopt:64:seed=3 --config varopt:256:seed=2 --config varopt:256:seed=3 \
--config varopt:64:reduce=step --config prio:64 --config prio:256 --config coord:64 --config coord:256 \
--oracle lastspend-2022.u32 --out A --limit all --every 16 --rows-every 16 --bucket 10000000 \
--laplace-ref colors.laplace.zst --moments-ref colors.moments.zst \
--bands-ref colors.bands1024.zst --stats < finalBCUTXO_2022.scm
# pass B: the whole chain, k = 512 and 1024 (no binned reference)
sketch chain --config varopt:512 --config varopt:1024 --config prio:1024 \
--oracle lastspend-2022.u32 --out B --limit all --every 16 --rows-every 16 --bucket 10000000 \
--laplace-ref colors.laplace.zst --moments-ref colors.moments.zst --stats < finalBCUTXO_2022.scm
# section 8's tables from the three passes above (reads files only, refolds nothing)
sketch summarize --chain A --chain B --eval eval3m --moments colors.moments.zst --out tables
# the cost emits (k = 64, 128, 256; and k = 512, stopped at about 400M records):
# splitcount, a small C helper outside the crate, cuts the binary stream at record
# boundaries into 10M-record stretches and pipes each through its own `zstd -q -T16 -12`,
# writing raw and compressed bytes per stretch; nothing is stored
sketch emit --config varopt:256 --oracle lastspend-2022.u32 --limit all --stats \
< finalBCUTXO_2022.scm 2> emit.k256.err | splitcount 10000000 tmp256 > stretches.k256.tsv
# the two --long=27 runs: the same through splitcount2, which takes the zstd options
# production (section 9)
sketch emit --config varopt:512 --oracle lastspend-2022.u32 --limit all --stats \
< finalBCUTXO_2022.scm 2> emit.err | zstd -q -T16 -12 --long=27 -o colors.sketch-varopt512.zst7.11 The output format#
From encode.rs, integers as LEB128 varints, z() zigzag, floats little-endian:
header: "SKETCH01" | u32 version=1 | u8 variant (0 varopt, 1 prio, 2 coord)
| u8 reduce (0 record, 1 step) | u8 cap (0 min, 1 harm) | u8 0
| u32 k | u64 seed | u32 floor | u32 0
record: varint z(tx - (prev_tx + 1)) prev_tx starts at u64::MAX
u8 tag bit 0: shared form, bit 1: reduced
[f32 tau | f32 (raw_mass - 1)] only when reduced
tag bit 0 clear: varint n | n x varint db | n x f32 p
tag bit 0 set: f32 w* | varint m | m x varint db (p bit-equal to w*)
| varint h | h x varint db | h x f32 p
trailer: "SKEND001" | u64 records | u64 sum over records of (tx ^ n), wrappingTwo facts shape it. Block ids sampled from a colour hundreds of thousands of blocks wide
have nearly incompressible gaps, so they are written as varint deltas. And all the light
terms of a varopt sketch carry the same weight, over the total, so the shared
form stores that weight once and then only the blocks that have it: four bytes saved
per light term, most of a sketch. The encoder does not know which variant wrote a
record; it uses the shared form whenever the most frequent f32 bit pattern occurs at
least twice, which is lossless whatever wrote it. The reduced bit tells a reader which
colours are exact (a record without it is the colour, up to f32). The format is
meant for zstd. The encoder’s notes recommend plain -12 without --long, because
--long=30’s 1 GiB window must then be passed to every decoder; --long=27 (a 128 MB
window) avoids that, since it decodes with a plain zstd -d (verified with cmp), and
production uses it. Those notes, and the production line in sketch.rs’s documentation
(sketch emit ... | zstd -T16 -12), predate this choice.
7.12 The share matrix on disk#
This subsection, like §7.3, is about the main binary. The solve of §5.2 has one
coefficient matrix, , and every run rebuilds it by parsing the 149,968,404,213
bytes of the records, 193 bytes a record on average, for the five things the fold reads:
the block, the transaction id, each input’s amount and the transaction it spends, and the
number of outputs. Every projection, every change to what is emitted rather than to what
is folded, pays that parse first. The main binary’s examples/matrix.rs writes
once, in one pass, and --matrix reads it back in place of the records (a run
given both a matrix and records on its input is refused):
cargo build --release --example matrix
./target/release/examples/matrix --compact chain2022.foldmat < finalBCUTXO_2022.scm # 401.2 s
./target/release/examples/matrix --check chain2022.foldmat < finalBCUTXO_2022.scm # 461.6 s, 8 MB
./target/release/examples/matrix --verify chain2022.foldmat # 110 s, 5.4 MBexamples/matrix writes, against the records. Sizes and times from the crate’s README.md, RUNNING-2022.md and src/matrix.rs (runs of the main binary’s example, wall times; the file itself was not kept).| the 2022 chain as | bytes | against the text | exact |
|---|---|---|---|
records, finalBCUTXO_2022.scm | 149,968,404,213 | 1.0× | yes |
--csr, u32 row pointers, u32 columns, f32 shares | 19,473,632,380 | 7.7× | no |
--compact, the default | 10,601,433,514 | 14.1× | yes |
--structure, no amounts | 6,126,089,724 | 24.5× | shape only |
--check reads the compact file back against the records, field for field: 778,613,440
records and 2,044,897,328 inputs (one entry each; a repeated parent is not merged on
disk), every block id reconstructed from the coinbase rows
alone, the content hashes agreeing. --verify asks the same question without the
150 GB, sweeping the matrix alone against its header’s hash and counts, and it exists
because a fold does not check one: of 347,416 single-bit flips inside the rows of a
20,000-record matrix, the reader’s per-row invariants accept 102,220, and a flip at byte
700,007 of a 500,000-record matrix folds to exit status 0, an empty stderr and a different
answer. The row checks catch a damaged shape; only the hash catches a damaged number. The
fold does not pay the 72% the hash adds to a sweep, and could not use it if it did: a
hash settles at the last row, and the fold’s output streams from the first.
The 19.5 GB was the lossy one. The obvious binary form, a CSR with f32 shares, is
what --csr still writes, so that its loss is measured rather than argued. An f32 share
has a worst relative error of , and only 28.10% of the chain’s
shares round-trip at all; the sum of a row’s shares, within of one
in f64 (§5.1), drifts by up to before the fold composes
anything; and replaying the fold on those shares changes 44.71% of the --sum lines and
98.92% of the coefficients of the terms output. The same f32 is harmless in a sketch
(§7.2), whose error is that of a -point estimate; in an exact solve it is the only
error. The fix is not a wider float. A share is and both are
integers, so the compact file stores the raw u64 satoshi amounts, which is exact and
smaller (4.48 GB of deltas against 8.18 GB of f32): amounts within a row are nothing
like uniformly distributed, and a float is 32 bits of entropy by construction.
| section | bytes | share | what it is |
|---|---|---|---|
| columns | 5,317,886,057 | 50.2% | 2,044,897,328 parents, zigzag deltas along each row |
| amounts | 4,475,343,790 | 42.2% | 1,475,397,681 satoshi values, zigzag deltas |
| heads | 804,399,854 | 7.6% | one byte a row: input and output counts, a nibble each, and escapes |
| blocks | 762,261 | 0.0% | one varint per coinbase row, none elsewhere |
| header and indexes | 3,041,552 | 0.0% | the 64-byte header; GROUPS, 16 bytes for each of the 190,092 groups of 4,096 rows; TXFIX, the four rows where the id breaks its sequence (the BIP-30 duplicates and the steps back), in 12 bytes, and the two counts |
README.md and src/matrix.rs. The last row is the remainder of the total, 64 + 190,092 × 16 + 16 bytes; the README.md’s 3,041,488 leaves out the header.Three rows of Table 5 are the case against a CSR’s fixed
widths. A u32 row pointer costs 3.11 GB to hold a count whose median is 1, where a
nibble and an escape cost 0.80; a u32 column costs 8.18 GB where a delta costs 5.32; and
73.14% of the rows have a single input, whose share is exactly 1 on both branches of the
share rule, so 569,499,647 amounts need not exist. Those single-parent records are among
the ones that answer their parent’s Rc in §7.2.
Two transforms were measured and refused, and both are reserved as flag bits a reader
refuses, so that neither is re-derived later and quietly believed. Sorting each row’s
parents would save 0.89 GB of the delta chain and change 4.06% of the --sum lines,
because the fold walks a row’s inputs from the last to the first (§7.5) and
reassociating an f64 sum moves its last bits. Deduplicating a row that spends the same
transaction twice would save 0.13 GB and free that colour at the wrong instant, for the
reason §5.3 ends its oracle on: the fold counts the multiplicity down, and the oracle frees
a colour on the lowest input index that names it.
A run off the records and the same run off the matrix print the same bytes. The largest
checks are a --sets pair of 294.6 GB a side at 2,000,000 records and --bands 1024 --moments at 20,000,000 records, 1,149,593,609 bytes a side, and --rings and --sets
still hash alike off a matrix. What the matrix saves is less than the size ratio: over
20,000,000 records, 17.8 s off the text against 11.7 s off the matrix with the fold as
cheap as it goes (--bands 1 --sum), and 70.5 s against 63.9 s at --bands 1024 --moments, where the fold is most of the work, both with the records warm in the page
cache; cold, the two files are 12.5 minutes of reading against 50 seconds. What the matrix
buys is not a faster fold but a parse paid once. The whole-chain colors.bands1024.zst of
§5.2 was folded off it. sketch does not read the matrix: its runs parse the text.
7.13 The tests#
cargo test --release --bin sketch -- --include-ignored passed 106 of 106 at the time
of the runs of section 8, and 139 of 139 with the stores of section 10. At commit
adfe031, with the modes that read the runs back, cargo test --release --bin sketch
passes 196 and ignores 4: the two integration tests that read the chain’s files, the
coord bias test below and a benchmark, which --include-ignored runs. What they
assert:
- Randomness (T1).
splitmix64’s golden value;unitstrictly inside at both ends and over a million draws; streams deterministic and distinct across salts and seeds. - VarOpt, deterministic (T2). Over 1,000 random draws 64 offsets (61,056 reductions; the draws with are skipped, since the caller stores those untouched): output ascending, a subset of the input, heavies kept with their weight, lights at , to relative, and, except in events, exactly points, the mass to and every CDF gap below (Theorem 3); fewer than 64 events in those 61,056 reductions. The iterated threshold equals the sorted one on 2,764 cases (3,000 draws, skipped), including geometric weights and many-way ties; a few items holding all the mass but a tail of weights near never overflow .
- VarOpt, statistical (T3). Over 200,000 offsets, every coordinate’s mean estimate is its weight, every light’s inclusion frequency is , and the mean Laplace value at is exact, all within 5 standard errors.
- prio (T4). The mean raw Horvitz–Thompson weight of every coordinate is its weight within 5 SE, and the output always has points.
- coord (T5, T6). Lemma 17 bit for bit in the
f32world, nested; step mode with the binary cap;cap=harmkeeps a rank prefix of whatcap=minkeeps; against the exact store on overlapping DAGs, stored weights are lower bounds and an infinite means exact. - The driver (T7, T8). With at least every support, every variant in both reduce
modes, with and without the oracle, emits the exact colour; with , every
record whose exact support is at most 64 comes out exact; with every
variant matches the exact store, and the exact store matches a direct reimplementation
of
run()’s fold bit for bit. - Through a DAG (T9, T10). Over 2,000 seeds on a synthetic DAG,
varopt’s emitted estimate andprio’s raw weights are unbiased within 5 SE, block by block and for the Laplace value;varopt’s mass stays within of one at every record.coord’s bias is documented by an ignored test rather than gated: worst . - Format and determinism. Emitted bytes decode to the text emitted directly, metadata included; the same seed writes the same bytes, another seed does not.
- Integration. The first 100,000 records of the chain with , transaction
by transaction, against
coloring-bt-transactions 100000 --weighted: worst absolute error , worst relative error for coefficients of at least . - The permutation (T-K1).
Permis a bijection withblock(rank(b)) == bon all of for bits 12, 16 and 20 and three seeds, with its first ranks pinned; seeds share fewer than 1% of fixed points; a block past the universe is a hard error. Over seeds at 12 bits the rank of a fixed block passes a test on 64 cells (), and the ranks of two blocks show no correlation. - Capped merges (T-K2). The two-way merge, the tree and the heap equal a brute-force bottom- of the union, with the truncation flag exact, over random runs with overlaps, identical and empty runs, .
- KMV through the driver (T-K3 to T-K5). On the synthetic streams of T7 (shared
parents, repeated inputs, zero amounts, all-zero records, one-group records, the
BIP-30 duplicate) and on a random DAG, with and without the oracle,
: every sketch is the bottom- of the brute-force support,
fullholds exactly when the support exceeds , a whole sketch’s count is the support’s size, thesetssupport equals the exact store’s terms and thepossupport its positive-share reachability; permuting or splitting operands changes no byte. A block diluted -fold at each of 30 steps ( in all), whosef64coefficient underflows to 0, stays in thepossupport. - Estimators over 2,000 seeds (T-K6 to T-K8). The count over both universes (including dense subsets of ) and the restricted union count are unbiased within 4 SE, with RMS within 10% of the formula; Jaccard is exact when both sketches are whole, also when their union exceeds (where the textbook form is not), and over its mean is within 4 SE and its SD within 10% of the hypergeometric value; containment is NaN exactly when its sample is empty and otherwise unbiased within 4 SE where its sample is large.
- The projection (T-L1 to T-L4). The L1 store’s vector equals computed from
the exact colour, through the grouped and the free path, to relative in
f32and inf64; over 400 seeds at and the scale MLE has a relative bias of at most 2% and a relative SD times in (); identical colours give exactly, disjoint ones a value within of 1, injected infinities a finite one; two seeds are uncorrelated. - Streams and modes (T-K9, T-K10, T-P1, T-P2, T-E1). The count stream round-trips
with its checksum at fixed width,
decodedispatches on the magic and still writes the old text forSKETCH01; the same seed writes the same bytes;pairsequals the pure estimators and is byte-identical at 1 and 8 threads;pickcaptures each selected record once;evalfinds no set mismatch; damaged headers are an error, not a panic; the new modes refuse options they would ignore. - Integration (T-I1). The first 1,000,000 records of the chain at against the exact support sizes: exact wherever the support has at most blocks, and every seed gate of a 16-seed family at passes.
- The modes that read runs back. Their sums, medians and linear quantiles equal
numpy’s on values numpy printed;
summarizeandpairs-statsreduce a small sweep and a smallpairsrun end to end, andselect’s file reads back; the exact surface is the same at any thread count; and the old modes refuse the new modes' options.
8. Results#
8.1 What was measured#
- Pass A (
chain, the whole chain, 14 stores in one pass):varoptat ; seeds 2 and 3 at and ; step mode at ;prioandcoordat and ; with the 1024-band reference. - Pass B (
chain, the whole chain):varoptat and andprioat , one seed, without the band reference. It took 11 h 43 min (wall time from/usr/bin/time -v) and peaked at 164.4 GB of resident memory for the three stores together (thevm_hwmcolumn of itscost.tsv). - eval3m (
eval, the first 3M records, every 200th record, 15,000 rows a configuration): every sketch against its whole exact colour and against the same variant’s single-shot reduction of it. - Cost emits (
emitcut into 10M-record stretches, each compressed by its ownzstd -T16 -12, §7.10):varoptat over the whole chain, and at until it was stopped at about 400M records; two more with--long=27.
The accuracy tables use every 256th record (--every 16 --rows-every 16, §7.10; 3.04M
rows), restricted to reduced rows: a larger keeps more early colours exact, which
would lower an all-rows average for a reason that has nothing to do with how well a
sketch approximates. Errors in blocks are
converted from fractions of ; a day is about 144 blocks. Labels: [M] measured,
[P] projected from measurements, [E] a rougher estimate (an extrapolated
compression ratio). Every number below comes from those runs, whose commands are in §7.10.
One more mode turns their outputs into the tables of this section: sketch summarize
reads each pass’s per-record rows, buckets.tsv, seeds.tsv and cost.tsv, and
eval3m’s rows.tsv and summary.tsv, groups the rows by 100M-record stretch (S0 to
S7, S0-2 for the first 300M, pooled for the whole chain) and writes one TSV per
kind of table, without rerunning a fold (--moments adds the floors of §8.8):
sketch summarize --chain A --chain B --eval eval3m --moments colors.moments.zst \
--out tablesThe Python scripts that first made these tables agree with it at every digit printed
here (the means and quantiles of the reduced rows to relative; the
rest differ only by how pandas parses long decimals). Each subsection names the file of
tables/ its results come from.
8.2 Error against #
| mean |Δmean| (blocks) | p90 |Δmean| (blocks) | mean |Δmean|/sd (%) | mean max |ΔLaplace| (×10⁻³) | mean |Δsd|/L (×10⁻³) | |
|---|---|---|---|---|---|
| 16 | 9,401 | 19,186 | 6.17 | 16.7 | 4.30 |
| 32 | 4,951 | 10,174 | 3.25 | 9.18 | 2.33 |
| 64 | 2,580 | 5,330 | 1.69 | 4.89 | 1.22 |
| 128 | 1,333 | 2,759 | 0.873 | 2.53 | 0.615 |
| 256 | 686 | 1,426 | 0.446 | 1.29 | 0.301 |
| 512 | 349 | 729 | 0.225 | 0.659 | 0.143 |
| 1024 | 178 | 372 | 0.114 | 0.338 | 0.070 |
prio 64 / 256 / 1024 | 15,303 / 7,585 / 3,731 | 33,373 / 16,500 / 8,158 | 9.74 / 4.80 / 2.35 | 24.1 / 12.0 / 5.92 | 9.69 / 4.60 / 2.25 |
coord 64 / 256 | 67,482 / 59,072 | 121,513 / 105,765 | 39.4 / 34.5 | 71.0 / 61.6 | 12.2 / 13.4 |
sketch summarize, errors.tsv, group pooled.varopt follows
the guide from 16 to 1024; prio follows ; coord barely moves.varopt’s error halves with every doubling of , with no floor up to
(Figure 2). Over
the log-log slopes are to for
, , the Laplace errors at
, the largest Laplace error and the binned ; and for
and , the far tail that small sketches undersample. The
local slopes steepen with : about for from
256 to 512 and from 512 to 1024 over the whole chain ( on 0–300M). An approximate
law is
the product drifts from at
to at . The slopes are slopes.tsv (an OLS fit per metric and
run of consecutive ), the product is errors.tsv’s k_times_mean_abs_dmean_over_sd.
8.3 Error against depth#
errors.tsv, groups S0 to S7.| stretch (records) | exact sd (blocks) | : |Δmean|/sd (%) | : |Δmean|/sd (%) | ||||
|---|---|---|---|---|---|---|---|
| 0–100M | 774 | 396 | 201 | 102 | 81,722 | 0.241 | 0.121 |
| 100–200M | 1,016 | 522 | 265 | 134 | 117,957 | 0.224 | 0.113 |
| 200–300M | 1,132 | 579 | 294 | 149 | 131,579 | 0.222 | 0.112 |
| 300–400M | 1,328 | 683 | 349 | 179 | 156,036 | 0.223 | 0.114 |
| 400–500M | 1,433 | 746 | 381 | 195 | 173,760 | 0.218 | 0.111 |
| 500–600M | 1,561 | 803 | 409 | 209 | 187,386 | 0.219 | 0.111 |
| 600–700M | 1,661 | 853 | 434 | 221 | 190,819 | 0.228 | 0.116 |
| 700–778.6M | 1,835 | 940 | 481 | 249 | 210,306 | 0.230 | 0.119 |
varopt’s
error grows by about 1.8× from 100–200M to the end, exactly as the colours’ own spread
does; relative to that spread (right) it is flat at every . coord’s relative error
keeps growing. Drawn from buckets.tsv of passes A and B.There is no accumulation with depth (Figure 3). The error in blocks grows, by about 1.8× from
100–200M to 700–778.6M at every , because the colours themselves spread out (their
exact sd goes from 118k to 210k blocks). Relative to the spread it is flat: the ratio of
the last stretch to 100–200M is 1.01–1.02 for , 1.03 at and 1.05
at . The deepest stretch is still the one to plan against: its p90 is 3,677 /
1,896 / 978 / 503 blocks for . One thing does grow:
varopt’s , by 1.12–1.28× with depth at
(prio’s by 1.8×). As §6.3 explains, the flatness is measured, not proved. The ratios
are in depth.tsv, the p90s in errors.tsv at S7.
8.4 The variants compared#
priofalls as (slopes to ; from 256 to 1024), as the argument after Proposition 13 predicts. Its error is 5.9×varopt’s at , 11.1× at and 20.9× at :prioat 1024 is worse thanvaroptat 64, andprioat 256 is worse thanvaroptat 32. Against its own single-shot reduction on exact colours (eval3m, colours above 32,768 blocks) the recursivepriois to off: the recursion adds nothing, and its whole error is the sampling error of one priority-sampling reduction.coorddoes not improve with and is mostly bias. Its slopes from 64 to 256 are to ; its error relative to the spread grows 2.1–2.3× along the chain (depth exponent 0.8–0.9 for ); and its signed mean is 0.99 of its mean absolute error for mean and for and (0.94–0.95 for , 0.61–0.80 for ). Its estimated colours are systematically too late. On eval3m its excess over its own single shot grows with (KS and at ). This is §6.6 at scale.
The slopes are in slopes.tsv (the ranges leave out TV1024, §8.8), the multiples of
varopt in errors.tsv, coord’s depth in depth.tsv and its signed ratios in
signed.tsv, the eval3m excesses in ideal.tsv.
8.5 Bias#
varopt seeds
stay within a few hundred blocks of zero (RMS about 70 blocks over the 78 buckets),
while prio swings by up to about 1,800. Right, signed mean over mean absolute error:
coord sits at , all bias. Drawn from pass A’s buckets.tsv; the RMS and the
largest swing are in signed.tsv.varopt is unbiased by Theorem 7, and the chain does not contradict
it (Figure 4), but the test is weak. Rows of one run share sketches and ancestry, so per-row
standard errors understate the spread of a mean many times over (by 3× to 35× on the
first 600k records; that produced “biases” at that 16 seeds showed were not
there; design-phase prefix runs, not a crate run). The honest test uses independent
seeds: three at and at , whole-chain count-weighted signed means,
with 2 degrees of freedom.
- at and at over mean and the seven Laplace values ().
- The 95% bound on , , is at most 11.4% of the mean absolute error at and 16.7% at . Three seeds cannot do better than that.
- Per stretch, none of the 128 values exceeds the critical 4.30 (the largest is ); per 10M bucket, 1–2 of 78 reject at and 2–6 of 78 at , against about 3.9 expected (and buckets are serially correlated).
- On eval3m with 4 seeds, and in an earlier 12-seed check on a prefix of the chain: .
- and were run with one seed and were not tested for bias.
The tests are bias.tsv (with the bound as bound_over_abs) and bias_buckets.tsv; the
eval3m are eval’s own seeds.tsv; the 12-seed check is the same mode over the
verification’s 10M-record prefix run:
sketch summarize --chain chain10m-seeds --stretch 5000000 --out verify10m8.6 Record mode against step mode#
varopt at : the error of the literal pairwise fold (a reduction after every
combine, seed 1) over the mean error of one reduction per record at seeds 1–3, per
bucket, from pass A’s buckets.tsv.Step mode is worse at every depth (Figure 5): over the whole
chain, against the mean of three record-mode seeds, 1.49× for
, 1.72× for , 1.34× for the
largest Laplace error, 1.24× for , 1.46× for binned and 1.51× for the
band-edge KS, between 1.18× and 2.02× per stretch, with
the least uniform (1.26× before 100M, 1.75–2.02× after 200M). It did 6.15× the
reductions (1,219,272,266 against 198,333,465) for about the same CPU time (3,951 s
against 4,048 s of fold time), and on eval3m it multiplied the KS and excess over
the single shot by 2.2–2.6×. The ratios are in step.tsv, the reductions and fold
times in cost.tsv, and the eval3m factors are step mode’s paired excess in
ideal.tsv over that of record-mode seed 1, in stratum fix:>32768 at and
.
8.7 The recursion against a single reduction#
varopt, in percent. Drawn from eval3m’s
summary.tsv and rows.tsv.ideal.tsv, stratum fix:>32768.| metric | excess at | excess at |
|---|---|---|
| KS | +66% | +235% |
| +31% | +97% | |
| TV over 1024 bands | +1% | +52% |
| |Δmean| | +29% | +67% |
The recursion has a price (Figure 6 and the table above), and it
grows slowly with , but all three errors keep falling:
the recursive KS, and largest Laplace error fall as , and
over to , the single shot as , and
. For colours of 4,097 to 32,768 blocks the excess is only +2% to +28%
(stratum fix:(4096,32768]); the exponents are ideal_slopes.tsv. And the price does
not grow with depth (§8.3).
8.8 Floors: what TV1024 cannot say#
A sketch of points of a colour spread over thousands of bands cannot have a small total variation over 1024 bands, however good it is. Recomputed with each row’s own , the single-shot VarOpt lower bound on TV1024 is 0.883, 0.746 and 0.375 against the measured 0.919, 0.818 and 0.540 at : at least 96%, 91% and 69% of the measured TV1024 is sampling floor, so it does not measure the recursion at and is left out of the comparisons. The band-edge KS has a floor of about (the remark after Corollary 4; single-shot KS measured at 0.741–0.750 for to ), which on eval3m is about 60% of the measured value at , falling to about 40% at and 30% at (one over one plus the KS excess of Table 8). The binned has no hard floor (on eval3m the single shot is 60–77% of the measured value for , falling to about 51% at ). So is chosen on , its p90, the Laplace errors and .
The floors are in the tables --moments adds: floors_chain.tsv (floor_lb_own_tau,
and its share of the measured tv) and floors_eval.tsv (ideal_ks_over_tau,
ideal_w1_over_w1); the KS shares are one over one plus ideal.tsv’s excess.
8.9 Cost#
| config | mean / p90 |Δmean| (blocks) | ≈ days (mean / p90) | peak RSS | wall time | zstd -12 | -12 --long=27 | status |
|---|---|---|---|---|---|---|---|
varopt 64 | 2,580 / 5,330 [M] | 17.9 / 37 | 8.5 GB [M] | 1.1 h [M] | 31.3 GB [M] | ~20 GB [E] | Pareto |
varopt 128 | 1,333 / 2,759 [M] | 9.3 / 19 | 12.4 GB [M] | 1.8–2.0 h [M] | 65.6 GB [M] | 41.7 GB [M] | Pareto |
varopt 256 | 686 / 1,426 [M] | 4.8 / 9.9 | 20.3 GB [M] | 3.4 h [M] | 144.5 GB [M] | ~86 GB [E] | Pareto, fallback |
varopt 512 | 349 / 729 [M] | 2.4 / 5.1 | 36.3 GB [M] | 5.1 h [M] | ~312 GB [P] | 172.7 GB [M] | Pareto, chosen |
varopt 1024 | 178 / 372 [M] | 1.2 / 2.6 | ~68 GB [P] | 11.4–11.9 h [P] | 659–721 GB [P] | ~380–420 GB [E] | Pareto, for a tight tolerance |
varopt 64, step mode | 3,866 / – [M] | 26.8 / – | ≈ varopt 64 [E] | fold time 0.98× varopt 64 [M] | ≈ varopt 64 [E] | – | dominated |
prio 64 | 15,303 / 33,373 [M] | 106 / 232 | ≈ varopt 64 | fold time 1.07× varopt 64 [M] | not measured | – | dominated |
prio 256 | 7,585 / 16,500 [M] | 53 / 115 | ≈ varopt 256 | fold time 1.12× varopt 256 [M] | not measured | – | dominated |
prio 1024 | 3,731 / 8,158 [M] | 26 / 57 | ~68 GB [P] | ≥ varopt 1024 | not measured | – | dominated |
coord 64 | 67,482 / 121,513 [M] | 469 / 844 | ≈ varopt 64 | fold time 0.77× varopt 64 [M] | not measured | – | dominated |
coord 256 | 59,072 / 105,765 [M] | 410 / 734 | ≈ varopt 256 | fold time 0.64× varopt 256 [M] | not measured | – | dominated |
varopt, error against cost for to . Filled markers are measured, hollow
ones projected or estimated; the horizontal bars are ranges. Every doubling of
halves the error and roughly doubles the bytes and the time: there is no knee. The points
are the table’s cells, written into the plotting script by hand.Only the errors (errors.tsv) and the fold-time ratios (cost.tsv’s
busy_over_reference) come from sketch summarize. The rest was measured on the cost
emits of §7.10: peak memory by their --stats, and, outside the crate, wall times and CPU
shares by /usr/bin/time -v and bytes per 10M-record stretch by splitcount and a small
Python script. The [P] and [E] cells and the memory fit are hand projections.
Size. Measured with
zstd -T16 -12over the whole chain: 31.3, 65.6 and 144.5 GB at (raw 114.7, 212.8 and 411.9 GB), and 151.2 GB for the first 400M records at (raw 410.5 GB). Every run parsed all 778,613,440 records with a matching trailer (splitcountchecks it), and repeated runs wrote byte-identical output. The whole-chain size is projected by scaling the tail (400M records to the end) by the ratio: measured over 300–400M, that gives 313.6 GB (403 B a record; raw about 806 GB), and measured over 0–400M, 310.7 GB; at 659–721 GB (raw about 1.59 TB, which would not fit on the disk: the raw stream must never be written).--long=27(a 128 MB window) saved 36.4% at over the whole chain and 40.7% at over 0–350M; at the production run measured it over the whole chain, 172.7 GB (221.8 B a record), about 45% below the 312 GB projected without it. The , and figures with it are estimates. Compressed bytes peak at 580–650M records (238.2 B a record at for 600–610M), not at the slowest stretch (290–330M).Memory. Peak RSS (the VmHWM of
emit --stats, equal to/usr/bin/time -v’s, which alone gives the stopped emit’s; reported in KiB and given here in GB of bytes) 8.51, 12.39, 20.32 and 36.34 GB at . The fit(peak entries from
--stats) projects about 68 GB at , consistent with pass B. Live sketches hold about entries each at the peak. The machine has 503 GiB, so memory constrains no here.Time. 1 h 07 min, 1 h 47 min to 2 h 00 min, and 3 h 23 min at ; about 2 h 52 min to 400M records at , projected to 6.3–6.6 h for the whole chain (in pass A’s
bucket_cost.tsv, the 378.6M-record tail takes 1.22–1.28× the fold time of the first 400M at to , rising with ); the production run, with almost nothing beside it, took 5 h 06 min, so the projection, made from emits that shared the machine, was about 25% high. is projected at 11.4–11.9 h by the same method, and is probably high by a similar margin. The emit uses 120–135% of a core;zstd -12with 16 threads runs at 230–290 MB/s (a benchmark) against at most about 55 MB/s of output, so it is never the bottleneck.
8.10 The choice of #
The cost has no knee (Figure 7): every doubling of halves the error and roughly doubles the bytes and the time. So the rule is a tolerance: pick the smallest whose deep-chain p90 is below the tolerance a downstream analysis can accept for one transaction’s mean colour.
errors.tsv, group S7.| deep-chain p90 |Δmean| (700–778.6M) | ≈ days | |
|---|---|---|
| 1,896 blocks | 13 | 256 |
| 978 blocks | 6.8 | 512 |
| 503 blocks | 3.5 | 1024 |
Relative to a colour’s own spread the mean is
0.45%, 0.23% and 0.11% for , at every depth. With no stated
tolerance, is the default: it halves every error of , its memory is
measured, its output takes under a quarter of the 1,291 GB free on the disk (df) even
without --long, and it runs overnight. is feasible and halves the error
once more, but costs half the free disk at -12, a 12-hour run, and an emit whose size,
time and memory are all projected. , the only with everything measured, is
the fallback.
Pass B finished after this choice was made and confirmed it. The whole-chain
is 349 and 178 blocks for and (a ratio
of 0.51); the ratio of between the last
stretch and 100–200M is 1.03 and 1.05; pass B’s peak resident memory was 164.4 GB for
its three stores; its fold time at was 1.90× that at , and its wall
time 11 h 43 min; and prio at 1024 is 20.9× worse than varopt at 1024. All but the
wall time are in the files above (memory and fold times in cost.tsv).
9. The Production Run#
Started on 2026-11-13, with the build used for every measurement above:
sketch emit --config varopt:512 --oracle lastspend-2022.u32 --limit all --stats \
< finalBCUTXO_2022.scm 2> emit.err \
| zstd -q -T16 -12 --long=27 -o colors.sketch-varopt512.zstIt writes colors.sketch-varopt512.zst: for each of the 778,613,440 transactions, in
record order, its colour as a varopt sketch of at most 512 blocks ( in rare
rounding events), normalised to sum one, with the bit that says whether it is exact
(and, when it is not, its and raw mass), in the format of §7.11. It decodes with
a plain zstd -d piped into sketch decode, and sketch check recomputes from it the
error tables of a chain run.
It ran from 07:39 to 12:45, and the pipeline exited with status 0.
/usr/bin/time -v, the size from the file, the rest from the last line emit --stats wrote.| measured | projected before the run | |
|---|---|---|
| wall time | 5 h 05 min 56 s (fold busy 15,797 s; 131% of a core) | 6.3–6.6 h [P] |
| peak RSS (VmHWM) | 35,480,448 KiB = 36.33 GB | 36.34 GB (measured on 0–400M) |
colors.sketch-varopt512.zst | 172,702,042,699 bytes, 221.8 B a record | about 175–190 GB [E]; about 312 GB [P] without --long=27 |
| reductions | 198,939,818 | – |
| peak distinct live sketches | 7,593,630 | – |
| events | 0 | – |
No reduction rounded to : every sketch in the file has at most 512 entries.
Checked by reading it back. The file was decoded and scored against the exact references, independently of the run that wrote it:
zstd -dc colors.sketch-varopt512.zst \
| sketch check --out check --every 16 --rows-every 16 --bucket 10000000 \
--laplace-ref colors.laplace.zst --moments-ref colors.moments.zstIt took 1 h 03 min in 138 MB (from /usr/bin/time -v), read all 778,613,440 records,
and found the count and checksum of the file’s trailer correct. Its per-record error rows
(rows.varopt-k512-s1-rec.tsv, 3,041,459 of them, every 256th record) and its 2,496
bucket rows (buckets.tsv) are byte for byte those of the varopt-k512-s1-rec store of
pass B, which computed them in memory while folding. So
the file holds exactly the sketches whose accuracy section 8 reports: over the whole
chain, 349 blocks mean and 729 blocks p90 error on the mean block (Table 6, §8.2). A
plain zstd -d decodes it; a 128 MB window needs no flag.
A second product sits beside it: colors.kmv1024.counts.zst, the size of every
transaction’s support, counted by the coordinated bottom- of section 10, exactly when
the support has at most 1024 blocks and by an unbiased estimate otherwise. Section 10.11
says how to read it.
10. Counting and Comparing Colours#
Sections 5–9 read a colour through linear
functionals: its mean, its CDF, its Laplace values. Two questions about transactions are
not of that kind. From how many blocks does a transaction descend? And how much do two
transactions share? The varopt sketches cannot answer either (§10.2), and nothing about
them needs to change for the answers: two more stores, folded by the same driver beside
or instead of varopt, answer them, one exactly through the whole DAG (§10.3–10.5) and
one through a linear sketch (§10.6).
10.1 What is asked#
Both questions are about the support of a colour, the blocks it descends from, and the support has a recurrence of its own, the set-valued shadow of (1):
(5)It comes with two semantics, and every number below names which one it is about:
setskeeps every input, zero-amount ones included. It is what the repository’s--setscomputes, the exact sizes of the first 31,187,785 records are on disk (finalBCUTXO_2022.sets-counts.31187785.txt), and it is the default.poskeeps the operands with a positive share, : the blocks reachable through positive-share edges. In exact arithmetic this is , the support of the weighted colour, since is a sum over paths of products of shares. Inf64a coefficient can underflow to zero while its block stays reachable: record 2,499,382 has 96,213 terms, 9,392 of them exactly 0, every one an underflow. On this chain the two supports nearly coincide; their seed-1 count streams differ in 104 of the 31,187,785 records.
Three measures are asked of it.
Count, : the number of blocks a transaction’s coins descend from (under
sets, through zero-amount inputs too). §5.4 gives its scale: a median of about 174,000 blocks over the first 31.2M records.Jaccard similarity and containment, shared ancestry:
Weighted Jaccard similarity, shared value:
On this chain the last two say very different things. Among 255 deep transactions spread
over the first 3M records (the deep selection of §10.9, every support of at least
1,024 blocks), the median of a pair is 0.157 but the median is
, and 92% of the pairs have : old supports are largely
shared, while a colour’s weight sits on its recent blocks, which two transactions far
apart in time do not share. Inside a window of three blocks (the window selection) the
median is 0.994 and the median is 0.18. Over the whole chain the weights
overlap more: among 512 deep transactions spread from 2010 to 2022 (§10.10) the median
of a pair is 0.48 and the median estimated is 0.21, still 0.18 for pairs more
than 60,000 blocks apart. These medians are read off the pair runs R3 and R7 of §10.9 and
§10.10 by sketch pairs-stats (§10.8), in its quantiles.tsv (the 92% in
jw-strata.tsv).
10.2 Why the VarOpt sketches cannot answer#
The production file of §9 holds a sketch of every colour, and it is tempting to read counts and similarities off it. It cannot be done, for four reasons.
- Its randomness is fresh at every reduction (§6.2), so two sketches are not coordinated: a block in both supports is kept in both sketches only by coincidence, and the overlap of two kept sets does not estimate the overlap of the supports.
- Kept lights are carried at (Definition 1), so a kept light’s true weight, and with it its inclusion probability , is not in the sketch: a Horvitz–Thompson count over the kept set cannot be formed from it, even after a single reduction.
- A block dropped at an ancestor is gone for every descendant: the candidate of a record holds only blocks its parents’ sketches kept.
- Blocks reached only through zero-amount inputs have weight 0 and are skipped
(§6.2), so they are in the
setssupport and in no weighted sketch.
The weighted similarity has a natural plug-in, of the two sketches ( is a function of TV, §10.6), and it is biased low. With the two sketches, is concave, so by Jensen, block by block,
The sum of minima, , is biased low, and high. That alone does not sign the bias of the plug-in, a convex function of ; what does is the size of the loss on the light blocks. Heavy blocks are exact; a light block shared by two independent reductions is kept by both with probability and then counts , so it contributes about , far less than , and the plug-in came out low in every stratum measured (§10.9). Within one run the two sketches share the reductions of their common ancestors, so the bias depends on how many fresh reductions separate a pair from its common ancestry, and it grows with depth. Measured:
- Two independent
varoptsketches (, seeds 1 and 2) of the same colour give a plug-in with mean 0.963 and minimum 0, against the truth 1 (a design-phase prototype on the colours of the first 2M records, not a crate run). - On pairs of reduced colours with , the bias of the same-run plug-in grows from over records 0–1M to over 1–1.5M and over 1.5–2M (same prototype).
- On the prefix runs of §10.9 the same-run plug-in of
varopt:512underestimates by 0.171 on average over the 32,640 pairs of thewindowselection (mean 0.029 against 0.200), by 0.268 for and by 0.430 for (the table of weighted errors in §10.9, from thejw-strata.tsvofsketch pairs-stats, whose strata, weighted by their pairs, give the overall mean).
The plug-in is therefore not shipped; pairs writes it only to document this. The
Wasserstein distance between two varopt sketches has no such problem. It is a metric
under which each sketch is close to its colour (section 8 measures : a
reduction moves mass only between nearby blocks), so by the triangle inequality it is
off by at most those two errors. TV is a metric too, but under TV a sketch is far from
its colour, since its kept lights are carried at : that is the bias above.
serves below as a “temporal distance” between transactions.
10.3 A coordinated bottom- of the support is exact through the DAG#
A word on notation, as in §6. In the rest of §10, is a threshold on ranks, small ranks kept, as in §2 and §6.6, not the weight threshold of §6.1–6.5 and §10.2, to which §11 returns; and is the size of the permutation, the universe of §1.2.1.
Number the blocks with , and let
be a uniformly random permutation of , drawn once per run and shared by every
sketch: block has rank , and the ranks are what makes the sketches
coordinated. For a set of blocks let be its
elements of smallest rank. The kmv store keeps, for every colour, as an
ascending array of ranks and one bit, full, which says . A
sketch that is not full is the support. Throughout, , , are supports, which
are functions of the chain alone and independent of .
Lemma 20 (union). For any sets with union , . Hence any tree of pairwise merges, each keeping the smallest ranks of its two inputs, computes , in any order and grouping.
Proof. Let , so fewer than elements of rank below . If , fewer than elements of rank below , so . Hence with . For any such , : if then and ; otherwise contains the smallest elements of , and every other element of is an element of ranked above all of them, so the smallest of are those. The tree: by induction on its height, a node over the leaves , , whose two subtrees hold the leaves and , outputs
■
Lemma 21 (subsets). If and , then . In particular, for : if and only if .
Proof. The elements of ranked below are elements of ranked below , of which there are fewer than . For the second statement take ; the converse is . ■
Theorem 22 (exact through the DAG). Fold through the driver of §7.5: a coinbase of block is ,
not full; a record groups its operands by parent (under pos it skips those of share
0), answers the parent’s own sketch when one group is left, and otherwise merges the
groups’ sketches by capped merges, with full set when an operand is full or a merge
had elements left over. Then for every record the stored sketch is (or
) and full holds if and only if
(), whatever the fold order, the grouping, the repeated
operands, the zero amounts and the release oracle.
Proof of Theorem 22. By induction in file order; parents come earlier, so their sketches are
. A coinbase is . Operands that are the same parent are
the same set, and a union is idempotent, so grouping changes nothing; one group means
, and the parent’s sketch is . Otherwise
Lemma 20 gives . Full: if an operand is full,
; if a merge had leftovers, the union
below it exceeds . Conversely, if no operand is full, every operand is its whole
support, and if no merge had leftovers the root holds the whole union, so
. Under sets every operand is kept, which is
(5); under pos the skipped operands are exactly those outside
the union defining . The release oracle frees a colour after its last spender has
read it and never changes which colour an input reads, and a BIP-30 duplicate displaces
the older colour as in run(), the same for the support as for the colour. ■
This is Cohen’s size-estimation framework for reachability, in which min-rank sketches of the sets reachable from every node of a graph are computed by merges along its edges.Edith Cohen. Size-estimation framework with applications to transitive closure and reachability. Journal of Computer and System Sciences, 55(3):441–453, 1997. doi: 10.1006/jcss.1997.1534. URL https://doi.org/10.1006/jcss.1997.1534 Here the sets are a transaction’s ancestor blocks. So the fold has no recursion error. The sketch of a record at any depth is the one-shot bottom- of its support, a deterministic function of and , and every estimate read from it has exactly the law of a one-shot KMV estimate. This is the opposite of §6.3, where the whole difficulty was the error the recursion adds. What the records of one run do share is the permutation: their errors are correlated, and questions of bias are asked across seeds (§10.9).
The same argument gives what §5.6 and §6.6 said a coordinated merge could not have: exact weights.
Lemma 23 (kept weights). Let each sketch also store the colour weight of every kept block. Then for every record and every ,
the child’s kept weights are computed exactly from the parents’ sketches.
Proof. by (1). A term with
has in the support of , which is contained in
(in under pos, since
), so by Lemma 21: every
nonzero term is held by the corresponding parent’s sketch, and by induction with its
exact weight. ■
Remark 24. Lemma 21 is the property coord lacks. Its rank uses
the weight, which changes from parent to child, so a block can rank below the child’s
merged threshold and outside a parent’s sketch: in Example 18
block ranks 0.8 in , inside the merged threshold , and 4 in , outside
’s sketch, so its share from is unknown. Ranks that depend on the block alone
keep the lemma, and so would block-level priorities for any fixed
function of the block: a sample weighted by a prior rather than by the colour, which
§14 leaves open.
The exact weights were not shipped.The design-phase prototype stored them and, summing in the exact store’s order, matched the exact colour bit for bit on the kept blocks (14,219 sampled records of the first 3M, four values of : maximum difference 0). As an estimator of , though, a uniform sample of the support misses the few heavy recent blocks that hold most of the mass: the ratio over the kept blocks was biased upward by 0.051, 0.030 and 0.015 at , 256 and 1024 for pairs with . Weights also double the memory. §10.6 has a better tool for . The store keeps ranks only.
kmv store | |
|---|---|
| rank | a Fisher–Yates permutation of , seeded, 8 MiB of tables per seed (both directions) |
| why a finite permutation | the count is then exactly unbiased in the model actually run, and it can be restricted to the blocks a support can hold (§10.4) |
| an entry | 4 bytes (a u32 rank); the block is the inverse permutation of the rank |
| a sketch | at most ranks plus the full bit, behind an Rc of about 40 bytes |
| a record of distinct parents | by a balanced tree of two-pointer merges, each capped at ; one parent costs a reference-count bump |
| error added by the recursion | none: every sketch is the one-shot of its support |
| limit | blocks below ; a larger block is a hard error naming :bits= |
10.4 Counting#
Proposition 25 (KMV over a finite universe). Let be a set of blocks fixed independently of , with , and . If the sketch is not full, . If it is full, let be the number of blocks of ranked below the -th smallest rank of (the 0-based position of that rank among the ranks of ). Then satisfies exactly, and is an unbiased estimate of for .
Proof. The restriction of a uniform permutation of to orders uniformly at random, so the positions of among the positions of are a uniformly random -subset of , and is its -th smallest element. Choosing positions below and above,
Since ,
where the middle sum counts the -subsets of an -set by the position of their -th smallest element. Multiplying by gives . In the same way
and the -subsets of an -set, counted by the position of their -th smallest element, give
( throughout.) ■
Write for this estimator. Then, for , is an unbiased estimate of , since . The variance itself has no closed form, though it is a finite sum over the law of ; it is about
the continuous-hash value of §1.2.1 times the finite-population factor (§1.2.1 writes for the set size and for the universe). The approximation slightly overstates it: summed exactly over the law of (a numerical summation of the theory, outside the crate), for the variance is below it by under 1% at , under 3% at and up to 11.5% at . The seed tests of §10.9 check it on the chain.
The proposition leaves the universe free, and the choice matters. The textbook choice is the whole permutation, , with the -th smallest rank itself: . But every block of is at most , the newest block seen up to record (the record’s own block, on a chain read in block order), and is a function of the chain, not of . So is a valid universe with , and , the number of blocks ranked below the -th smallest rank of , gives
exactly unbiased as well and never above . Supports on this chain are dense in their universe: the supports of records 3,000,000 and 31,187,785 cover 70% and 84% of , so at the latter the finite-population factor is about 0.16 where ’s is 0.78. In the deepest stratum of the first 31.2M records (supports of 131,072 to 262,144 blocks) the theory RSE at is 0.0144 for against 0.0283 for : half the error, the gain a nearly four times larger would bring. The measured RMS over 16 seeds is 0.0152 against 0.0266, 57% of the error, the gain of a about three times larger. costs one query of a Fenwick tree over rank space per full record, into which the blocks are inserted as the chain’s newest block advances (§10.8). Both estimates are written; is the primary one.
10.5 Jaccard, containment and unions#
For two transactions with supports and and sketches , :
Proposition 26 (Jaccard). If neither sketch is full, is computed exactly from the two stored sets. If one is, let and , and put . Then is hypergeometric with population , successes and draws, so and
Proof. A sketch that is not full is its whole support. If one is full, , and by Lemma 20; since is fixed and uniform, is a uniformly random -subset of . By Lemma 21, an element of is in if and only if it is in , and likewise for , so : the number of successes among draws without replacement. Its mean is and its variance . ■
When neither sketch is full but their union exceeds , the textbook formula over
is still an estimate (it deviated by up to 0.0035 in the design-phase prototype); the
exact value is in hand, so it is used. In the even selection of §10.9, 208,335 of the
499,500 pairs have both sketches whole at and are computed exactly; in 57 of
them the union exceeds , where the textbook formula would have been an estimate
(both counts are columns of errors.tsv from sketch pairs-stats on R3).
Neither estimator uses everything: both sketches are complete below the smaller of their
two thresholds, so the union is known there, with between and elements, which
could lower the variance for small .Cohen and Kaplan’s estimators
for bottom- sketches use such samples, which hold more than the smallest of the
union.Edith Cohen and Haim Kaplan. Summarizing data using bottom-k sketches. In Proceedings of the Twenty-Sixth Annual ACM Symposium on Principles of Distributed Computing, PODC '07, pages 225–234. Association for Computing Machinery, 2007. doi: 10.1145/1281100.1281133. URL https://doi.org/10.1145/1281100.1281133
The union count is exact when neither sketch is full (the union is then in hand, whatever its size). Otherwise it is the count of , which the proof above has in hand, by Proposition 25 with the pair’s universe : exactly unbiased. The intersection is a product of dependent estimates: consistent, not unbiased.
The containment of in , , is read
from the part of ’s sketch that ’s sketch can vouch for. Let be the
-th smallest rank of when ’s sketch is full and otherwise, let
, and estimate the containment by
. is the set of elements of
ranked at most , and for each of them membership in is exact,
because ’s sketch holds every element of up to . So the estimate is a
ratio over a random subset of whose memberships are known exactly: consistent. It is
not unbiased, because depends on the ranks of , and with them on those of
; in particular the element at belongs to , so when
and that element is in , it is a sure hit in . That biases
the ratio up by about for a containment : the
full when is smaller than (0.004 at in a design-phase
simulation, not a crate run),
about half of it when the two are the same size, and none when is much larger. At
it is at most about 0.00025. With a strict
threshold, , the same simulation (20,000 permutations per case) showed
no bias within its standard error. The code keeps : at its bias is far
below every error measured in §10.9. The estimate is undefined when is empty, which
happens when is much smaller than : then has few elements below ,
about on average. pairs writes the size of
beside every containment, and the ratio as a flagged
fallback.
10.6 Weighted similarity: a function of L1, and L1 has a linear sketch#
The support’s sketch says nothing about weights. The weighted Jaccard similarity needs a different tool, and the shape of the colours makes it simple.
Lemma 27. For probability vectors and over the blocks , with ,
so
Proof. Coordinate by coordinate and . Summing over , the sum of minima and the sum of maxima add up to and differ by . ■
So of two colours depends on their L1 distance alone, and L1 distance has a
linear sketch: random projections by a 1-stable law, the Cauchy
distribution.Piotr Indyk. Stable distributions, pseudorandom generators, embeddings, and data stream computation. Journal of the ACM, 53(3):307–323, 2006. doi: 10.1145/1147954.1147955. URL https://doi.org/10.1145/1147954.1147955 Let be an matrix of
independent standard Cauchy draws , one column per block, drawn once per run
(coordinated, like ), and let the l1 store keep
for every colour.
Proposition 28 (the projection commutes with the recurrence). Fold through the driver: a coinbase of block is the column ; a record groups its operands by parent, skipping those of share 0, with groups, the parent of group and
its summed share, for ; it answers the parent’s own vector when one group is left (), and otherwise stores . Then in exact arithmetic for every record , at any depth.
Proof. By induction in file order: a coinbase of block has the colour , all its mass on , and is column ; otherwise
by linearity, where grouping only reassociates the sum, share-0 operands contribute 0, and one group has and . ■
There is no reduction, no , no per-record randomness: the only error is floating
point. The fold accumulates in f64 in group order and stores f32 (or f64); on the
first 3M records the stored vector matched computed from the exact colour to
relative in f32 and in f64 (§10.9).
For two fixed colours and , which are functions of the chain and independent of , the differences
are independent over and, by 1-stability, each is Cauchy with scale . The scale is estimated by maximum likelihood, one of the estimators of a Cauchy scale that Li, Hastie and Church compare:Ping Li, Trevor J. Hastie, and Kenneth W. Church. Nonlinear Estimators and Tail Bounds for Dimension Reduction in Using Cauchy Random Projections. Journal of Machine Learning Research, 8(83):2497–2532, 2007. URL https://www.jmlr.org/papers/v8/li07b.html the log-likelihood
is stationary where
whose left side increases from the number of zero to , so the root is unique (and when at least half the are 0, as for equal colours). The Fisher information of a Cauchy scale is per observation, so has relative SD about : 0.0625 at , 0.0442 at . The estimates are
whose SD is, by the delta method, about , at most (0.022 at ). The mean of would be the obvious estimator and has no expectation at all; the median is consistent but has relative SD , 11% more than the MLE.
The clipping leaves a floor. For disjoint colours (, ), with about normal with SD , and , whose mean is
0.0176, 0.0125 and 0.0088 at , 512 and 1024. Pairs with below a few hundredths cannot be resolved one by one; the unclipped is written beside for averages over many pairs. On the prefix, where the median of deep pairs across time is (§10.1), a weighted map would show only the floor. Over the whole chain it would not (§10.10: only a fifth of the pairs lie below the floor), but there the maps are drawn for windows of a few blocks, where is near 1 and is what tells transactions apart.
Why a linear sketch and not a weighted MinHash? Consistent weighted
samplingMark Manasse, Frank McSherry, and Kunal Talwar. Consistent Weighted Sampling. Technical Report MSR-TR-2010-73, Microsoft Research, June 2010. URL https://www.microsoft.com/en-us/research/publication/consistent-weighted-sampling/; and Sergey Ioffe. Improved Consistent Sampling, Weighted Minhash and L1 Sketching. In 2010 IEEE International Conference on Data Mining, pages 246–255. IEEE, 2010. doi: 10.1109/ICDM.2010.80. URL https://doi.org/10.1109/ICDM.2010.80 and P-MinHash, the
sampler of Moulton and Jiang,Ryan Moulton and Yunjiang Jiang. Maximally Consistent Sampling and the Jaccard Index of Probability Distributions. In 2018 IEEE International Conference on Data Mining (ICDM), pages 347–356. IEEE, 2018. doi: 10.1109/ICDM.2018.00050. URL https://doi.org/10.1109/ICDM.2018.00050 make two vectors'
samples collide with a probability equal to a weighted similarity, and their samples
are coordinated, as coord’s are. But a colour is a sum of its parents’ colours, and
for the simplest of these samplers no merge exists.
Proposition 29 (no merge under sums, for priority ranks). Let the sample of a nonnegative vector be , with
ranks ( when ) and , where the
are independent and identically distributed with a positive density on an interval
: exponential for P-MinHash, uniform for priority sampling and for coord’s
. Then no function satisfies
almost surely for all probability vectors .
Proof. Over four blocks take , and , and the event , , , , which has positive probability (it is open and holds at , scaled into ). On it and . But has ranks and sample block 2, while has ranks and a sample block other than 2, since . The same inputs to require two different outputs. ■
Samples of follow on the same event intersected with one on which further blocks, shared by all three vectors, have ranks small enough to fill the first places. The proposition is about this class only, ranks ; consistent weighted sampling as Ioffe defines it ranks by a randomised step function of , also nonincreasing in , and is not covered by the proof. The same samplers do compose under the coordinate-wise maximum: the rank of in is , so the bottom- of is the bottom- of the two samples merged. A union is a maximum of indicator vectors, and the support of a positive mixture is the support of the maximum, which is why the KMV of the support folds exactly and the weighted samples do not. Linearity is what survives the sum. Weighted sampling under sums is possible too, but only from a linear sketch. An sampler draws a block with probability about from a linear sketch of , so it folds through the recurrence as does.Hossein Jowhari, Mert Sağlam, and Gábor Tardos. Tight bounds for Lp samplers, finding duplicates in streams, and related problems. In Proceedings of the 30th ACM SIGMOD-SIGACT-SIGART Symposium on Principles of Database Systems, PODS '11, pages 49–58. Association for Computing Machinery, 2011. doi: 10.1145/1989284.1989289. URL https://doi.org/10.1145/1989284.1989289 Two such samplers, however, do not collide with probability , and for the L1 distance is all that is needed.
10.7 Other similarities from the same sketches#
Jaccard similarity and are two of many ways to say how much two transactions share,
and the three stores already written answer several others with no new fold.
sketch pairs-stats computes them from the outputs of pairs (§10.8):
against the exact values, where there are any, in similarity.tsv, and as quantiles in
similarity-quantiles.tsv.
Set similarities. Every classical similarity of two sets is a function of their sizes , and of their intersection :
the Sørensen–Dice coefficient, the cosine (Ochiai) coefficient, the overlap (Szymkiewicz–Simpson) coefficient, Kulczynski’s and the symmetric difference. Here and are the supports of two transactions, the blocks their coins descend from (§10.1), and the four ratios are best read through the two containments , the share of ’s ancestry that shares, and . Dice is their harmonic mean, cosine their geometric mean, Kulczynski their arithmetic mean and the overlap the larger of the two, so for every pair
with equality throughout when the two supports have the same size. They differ only in how they treat a pair of unequal ancestries, and on this chain that is the common case: an old transaction descends from few blocks, a new one from most of the past.
- Dice counts the shared blocks twice against the two sizes added, where Jaccard counts them once against the union. It ranks every pair as does and says nothing does not; it is the scale on which much of the literature reports overlap.
- Cosine is the geometric mean of the two containments. A small ancestry wholly inside a large one has but cosine : it penalises the difference in size less than Jaccard and Dice do.
- Kulczynski is the plain average of the two containments: how much of ’s ancestry is shared, and how much of ’s, weighted alike whatever their sizes.
- The overlap asks only whether the smaller ancestry lies inside the larger. It is 1 when every block the smaller one descends from is also an ancestor of the larger, however much more the larger has. For an older and a newer transaction it says whether the older one’s sources are all among the newer one’s.
- The symmetric difference is a count, not a ratio: the number of blocks that are in one ancestry and not in the other, the Hamming distance between the two supports read as bit vectors over the blocks. It says how many minting blocks separate two transactions, where the ratios say what share.
The kmv store estimates all three numbers: the counts by Proposition 25, the
intersection as (§10.5). Dice is a function of alone,
, and inherits its accuracy: the derivative is at most
2, and below 1 where is above 0.42. The others are ratios of dependent estimates, as the
intersection is: consistent, not unbiased, and clipped to where they are bounded.
The overlap is also the containment of the smaller support in the larger, and read that
way (§10.5, the smaller side by its estimated count) its memberships are exact.
The symmetric difference counts the elements outside the intersection, and the bottom-
of the union holds about of them, so its relative error is about
: fine for supports far apart, useless for near-copies.
Measured on the prefix, with R3’s 16 seeds at as the unit of the bias test (the runs of §10.9):
| measure | deep: mean | bias | RMS | window: mean | bias | RMS |
|---|---|---|---|---|---|---|
| Dice, | 0.375 | 0.012 | 0.981 | 0.0029 | ||
| cosine | 0.453 | 0.023 | 0.982 | 0.0039 | ||
| Kulczynski | 0.628 | 0.059 | 0.983 | 0.0039 | ||
| overlap, | 0.962 | 0.078 | 0.9999 | 0.0028 | ||
| overlap, as the smaller side’s containment | 0.962 | 0.0055 | 0.9999 | 0.00017 | ||
| symmetric difference, relative | 44,932 | 6.5% | 4,264 | 60% | ||
| Bray–Curtis , | 0.890 | 0.034 | 0.656 | 0.029 | ||
| Bray–Curtis, | 0.998 | 0.030 | 0.994 | 0.032 |
Dice, cosine and Kulczynski show no bias in any stratum of , and their RMS is that of
carried through their formulas. The overlap computed from the counts is biased low,
by 0.034 on deep and by 0.075 in its stratum : the true overlap is near 1,
because an older support lies mostly inside a newer one, and the noise above 1 is
clipped away. Read as the containment of the smaller support it shows no bias and an
RMS of 0.0055, a fourteenth of the other, and it is the one to use. The symmetric
difference is within 0.3% on deep, and fails inside the window, where is near 1:
13% low, with an RMS of 60% (66% in the stratum ).
Over the whole chain (R7, kmv:1024, seed 1, §10.10) inside each window the
medians of Dice, cosine and Kulczynski are 0.999, and the overlap is estimated at exactly 1
for at least 99.96% of the pairs: every sampled block of the smaller support is in the
larger one. Across the chain selection the medians are 0.65 (Dice), 0.70 (cosine) and
0.74 (Kulczynski), and the overlap is exactly 1 for 99.3% of the pairs where it is
defined; 1,025 of the 130,816 are not, the cells where the containment is not.
Weighted similarities that are TV. For two distributions and over the blocks, the Bray–Curtis dissimilarity is TV itself, since both sum to one,
and the histogram intersection , Czekanowski’s index
and the weighted Sørensen index are all (Lemma 27).
Read on two colours, TV is the share of value that would have to be moved from one minting
block to another to turn one colour into the other, however far it moves; and is the share of value the two have in common block by block, the part of each
transaction’s value that could be the same minted coins in the other’s. They answer the
question of on a different scale: is always at least , and the median of 0.21 of the whole-chain
pairs (§10.1) is a common share of 0.35. The l1 store answers them as it answers , from , and with the
same floor: in Table 13, is
within 0.004 where and 0.016 low where , which is the floor of
§10.6, , seen from the other side.
Distances between the VarOpt sketches. Every varopt sketch’s CDF is close to its
colour’s: Corollary 12 bounds the error at every cut, and
section 8 measures the KS distance itself. So a distance between CDFs on the block
axis is close too: KS is a metric, and by the triangle inequality the KS distance between
two sketches is off by at most the sum of their own KS distances to their colours, as is (§10.2), and unlike TV. The two read
the colours along the chain’s time axis. KS is the largest difference, over every block
height , between the shares of the two transactions’ value minted at or before :
at the point of the chain’s history where they differ most, how much more of one’s value
is older than that point than of the other’s. is the area between the two CDFs, in
blocks: how far in time, on average, value would have to move to turn one colour into the
other, and when one colour is older than the other at every height, the difference of
their mean blocks. TV and treat a block a day away and a block ten years
away alike; KS and do not. pairs writes KS beside : over the whole chain its median is 0.56 across the chain
selection and 0.06 to 0.13 inside the windows. pairs does not compute the exact KS of two
colours, so it is not checked here.
What would need a new store. The Euclidean distance, the inner product and the cosine of two colours need Gaussian projections in place of Cauchy ones, 2-stable rather than 1-stable,Piotr Indyk. Stable distributions, pseudorandom generators, embeddings, and data stream computation. Journal of the ACM, 53(3):307–323, 2006. doi: 10.1145/1147954.1147955. URL https://doi.org/10.1145/1147954.1147955 linear like and folded the same way. The Jensen–Shannon divergence could come from the maximally skewed stable projections that Clifford and Cosma use to estimate entropy, since the midpoint is linear.Peter Clifford and Ioana Cosma. A simple sketching algorithm for entropy estimation over streaming data. In Proceedings of the Sixteenth International Conference on Artificial Intelligence and Statistics, Proceedings of Machine Learning Research, volume 31, pages 196–206. PMLR, 2013. URL https://proceedings.mlr.press/v31/clifford13a.html Neither was built (§14). The Hellinger distance and the Kullback–Leibler divergence are not linear in the colour, and no linear sketch folds them.
10.8 Implementation#
Both stores are Algebras of their own, each on its own thread and fed by the same
parse as every other store (§7.10); the SKETCH01 format, the production file and the
varopt code are untouched, and the old modes write byte-identical output. That was
checked during the implementation against two references: the build of the commit
before the stores (f09847c), on emit, decode, eval, chain, check and the
first 300 MB of the production file’s decode; and the binary of the section-8 sweep, on
chain, an emit of 1M records and the first 1,000,000 records of the production
file’s decode. With the final binary, the one of every run below, the emit and
eval checks were repeated.
The permutation is a Fisher–Yates shuffleDonald E. Knuth. The Art of Computer Programming, Volume 2: Seminumerical Algorithms. Addison-Wesley, Reading, Massachusetts, 3rd edition, 1997. ISBN 0201896842. URL https://www-cs-faculty.stanford.edu/~knuth/taocp.html driven by the hash of §7.4, built once per seed and shared by every store of that seed:
pub fn new(seed: u64, bits: u32) -> Perm {
// …
let m = 1usize << bits;
let mut fwd: Box<[u32]> = (0..m as u32).collect();
for i in (1..m).rev() {
let j = (h3(seed, SALT_KMV, i as u64, 0) % (i as u64 + 1)) as usize;
fwd.swap(i, j);
}
let mut inv = vec![0u32; m].into_boxed_slice();
for (b, &r) in fwd.iter().enumerate() {
inv[r as usize] = b as u32;
}
Perm { bits, seed, fwd, inv }
}The modulo bias of each swap is below . A Feistel network would also be a bijection and needs no table, but even with ideal round functions it is not a uniform permutation, and both counts of §10.4 are proved exactly unbiased under one; Fisher–Yates with ideal swaps is exactly uniform.
The capped merge of two ascending runs of ranks stops as soon as it holds :
/// `K_k(a u b)` of two ascending runs into `out` (cleared first), equal ranks
/// once; answers whether anything was left over, i.e. whether the union has
/// more than `k` elements. It stops as soon as `out` holds `k`.
pub fn merge_cap(a: &[u32], b: &[u32], k: usize, out: &mut Vec<u32>) -> bool {
out.clear();
out.reserve(k.min(a.len() + b.len()));
let (mut i, mut j) = (0, 0);
while i < a.len() && j < b.len() {
if out.len() == k {
return true;
}
let (x, y) = (a[i], b[j]);
if x < y {
out.push(x);
i += 1;
} else if y < x {
out.push(y);
j += 1;
} else {
out.push(x);
i += 1;
j += 1;
}
}
let rest = if i < a.len() { &a[i..] } else { &b[j..] };
let room = k - out.len();
if rest.len() > room {
out.extend_from_slice(&rest[..room]);
true
} else {
out.extend_from_slice(rest);
false
}
}and a record is Theorem 22 in code. union_cap runs a balanced
tree of merge_caps, or a heap from 2,048 groups on; supports here are nested, so the
parents’ sketches nearly coincide and the heap, which pops every duplicate, was slower
than the tree below that (a benchmark during the implementation, over the first 15M
records at : 106 s of store time with a heap from 3 groups, 26–28 s with the
tree).
fn record(&mut self, ops: &[(KHandle, f64)], rec: u64) -> KHandle {
self.group(ops);
assert!(!self.groups.is_empty(), "record {} has no operand with a say in its support", rec);
if self.groups.len() == 1 {
// The union of one set with itself: the parent's own sketch.
return Rc::clone(&ops[self.groups[0]].0);
}
let groups = &self.groups;
let any_full = groups.iter().any(|&i| ops[i].0.full);
let k = self.spec.k;
let cut = union_cap(groups.len(), |g| &ops[groups[g]].0.r, k, &mut self.out, &mut self.scratch);
if cut {
self.work.reductions += 1;
}
let full = any_full || cut;
debug_assert!(self.out.len() <= k && (!full || self.out.len() == k));
Kmv::new(self.out.as_slice().into(), full)
}group collects the operands by Rc pointer, as Sketcher::group does (§7.6), and
under pos skips those of share 0. The restricted rank of §10.4 comes from a
Fenwick tree over rank space, grown block by block as the chain’s newest block advances,
so a whole run costs one insertion per block and one query per full record:
pub fn grow(&mut self, n: u64) {
while self.n < n {
let r = self.perm.rank(u32::try_from(self.n).expect("a block id fits in a u32")) as usize;
let mut i = r + 1;
while i < self.tree.len() {
self.tree[i] += 1;
i += i & i.wrapping_neg();
}
self.n += 1;
}
}
/// How many inserted blocks rank strictly below `r`.
#[inline]
pub fn below(&self, r: u32) -> u64 {
let mut i = r as usize;
let mut s = 0u64;
while i > 0 {
s += self.tree[i] as u64;
i &= i - 1;
}
s
}
// …
#[inline]
pub fn count_full(k: usize, n_univ: u64, below: u64) -> f64 {
(k as f64 - 1.0) * n_univ as f64 / below.max(1) as f64
}All pair estimates come from one merge walk over the two sketches, which reads membership off each side (Lemma 21), counts the first distinct ranks for the Jaccard similarity, and every rank for the containments:
pub fn pair_raw(a: View, b: View, k: usize) -> PairRaw {
let exact = !a.full && !b.full;
let (ta, tb) = (a.rk().unwrap_or(u32::MAX), b.rk().unwrap_or(u32::MAX));
let mut p = PairRaw { exact, ..PairRaw::default() };
let (mut i, mut j) = (0, 0);
let mut taken = 0usize;
while i < a.r.len() || j < b.r.len() {
// … the next rank `v` of the union, and whether it is in `a` and in `b`
if exact || taken < k {
taken += 1;
p.union += 1;
if in_a && in_b {
p.inter += 1;
}
if !exact && taken == k {
p.union_rk = Some(v);
}
}
if in_a && v <= tb {
p.t_ab += 1;
p.hit_ab += in_b as u64;
}
if in_b && v <= ta {
p.t_ba += 1;
p.hit_ba += in_a as u64;
}
}
// …
p
}pair_est turns these into (inter / union when exact, inter / k
otherwise), its hypergeometric SE, the intersection and the two containments, NaN when
their sample is empty.
The l1 store’s record is the sum of Proposition 28, with the
shares of repeated parents added first:
fn record(&mut self, ops: &[(LHandle, f64)], rec: u64) -> LHandle {
self.group(ops);
assert!(!self.groups.is_empty(), "record {} has no operand with a positive share", rec);
if self.groups.len() == 1 {
return Rc::clone(&ops[self.groups[0].0].0);
}
self.acc.iter_mut().for_each(|a| *a = 0.0);
for &(i, s) in &self.groups {
match &*ops[i].0 {
Vector::F32(v) => {
for (a, &x) in self.acc.iter_mut().zip(v.iter()) {
*a += s * x as f64;
}
}
Vector::F64(v) => {
for (a, &x) in self.acc.iter_mut().zip(v.iter()) {
*a += s * x;
}
}
}
}
stored(&self.acc, self.spec.prec)
}A coinbase is draws tan(pi (u - 1/2)) with u = unit(h3(seed, SALT_L1, b, j)),
always finite since unit is strictly inside (§7.4). The scale MLE solves its
equation by Newton’s method on , started at the median of
and safeguarded by a bisection bracket, so heavy Cauchy tails cannot throw it off:
pub fn cauchy_scale_mle(d: &[f64]) -> f64 {
let m = d.len();
// …
let half = m as f64 / 2.0;
let mut a: Vec<f64> = d.iter().map(|x| if x.is_finite() { x.abs() } else { f64::INFINITY }).collect();
let zeros = a.iter().filter(|&&x| x == 0.0).count();
if zeros as f64 >= half {
return 0.0;
}
let mid = a.len() / 2;
let med = *a.select_nth_unstable_by(mid, |x, y| x.total_cmp(y)).1;
// f(t) = sum 1/(1 + (a/s)^2) - m/2, f'(t) = sum 2 q (1 - q).
let f = |t: f64| -> (f64, f64) {
let inv = (-t).exp();
let (mut v, mut dv) = (0.0f64, 0.0f64);
for &x in &a {
let r = x * inv;
let q = 1.0 / (1.0 + r * r);
v += q;
dv += 2.0 * q * (1.0 - q);
}
(v - half, dv)
};
// … t = ln med; a bracket [lo, hi] with f(lo) < 0 < f(hi)
for _ in 0..200 {
let (v, dv) = f(t);
if v == 0.0 {
break;
}
if v < 0.0 {
lo = t;
} else {
hi = t;
}
let mut next = t - v / dv;
if !(dv > 0.0) || !(next > lo && next < hi) {
next = 0.5 * (lo + hi);
}
let done = (next - t).abs() <= 1e-12 || (hi - lo) <= 1e-12;
t = next;
if done {
break;
}
}
t.exp()
}Modes. Three modes use the stores, eval and decode learn them, and three more read
what they wrote, with no fold:
countfolds one store per--kmvand writes every record’s count as a fixed-width stream, comparing as it goes with the exact sizes of--sets-countswhere they exist. A whole sketch whose length is not the exact size, a full sketch of a support of at most , or a whole sketch of a larger one fails the run. It folds no colour, so it costs the parse and a capped merge per record.pickfolds any stores once (--config,--kmv,--l1, and the exact store with--exacton a prefix) and dumps the sketches of the records listed in a selection file. Which records are worth comparing (deep ones, a window, an even spread) is known only after acountrun, so selection is a second pass (select, below), and sketches of every record are never stored: at they would be about 3.2 TB.pairsreads apickdirectory and computes every pair of each group, by every measure it finds, with the exact values beside them when the exact store was dumped; it writes a long table and a square matrix per group and measure, byte-identical at any thread count.eval --kmv/--l1checks the sketches against the exact store on a prefix, anddecodereads a count stream; with--selectit cuts the records of a selection out of aSKETCH01file, which is how the productionvaroptsketches of selected records are read without a new fold.selectreads a count stream and writes the selection file thatpick --selectreads:select prefixthedeep,windowandevengroups of §10.9 from a prefix’s stream and the exact sizes,select chainthe four groups of §10.10 from the whole stream. It replaced the Python script that made the selections of R3 and R5, and writes the same two selection files byte for byte, in about 40 s where the script took 56 min on the whole stream (wall times).summaryreads stored count streams back, several of one run in lock-step, and writes what a whole-chain count is judged by once no reference is left: per stream and per range or bucket of records, the counts and their quantiles (beside the exact ones where--sets-countsreaches), the records counted exactly, the relative standard errorse / n_hat, and the seeds against each other (§10.10, §10.11).pairs-statsreads one or morepairsoutputs over the same rows, pooling their seeds, and reduces them to the bias, variance, agreement and quantile tables of §10.9 and §10.10, seeds as the unit, and to the other similarities of §10.7 (similarity.tsv,similarity-quantiles.tsv).
On the whole chain the exact colours exist only binned, in colors.bands1024.zst, and
three commands read them for a selection: pick --bands-ref copies the selected records'
lines of that file beside the fold, pairs --bands adds each pair’s binned TV, an exact
lower bound on the TV the L1 store estimates, and checks the L1 estimates against it
(§10.10), and describe compares the production varopt sketches that decode --select
cut out with their binned colours (§11).
The count stream (kmv.rs):
header (48 B): "KMVCNT01" | u32 version=1 | u32 k | u64 seed | u8 support (0 sets, 1 pos)
| u8 bits | u16 0 | u32 0 | u64 M | u64 0
record (20 B): u64 tx | u32 block | u32 m | u32 rk
m = len, with bit 31 set when full
rk = the 0-based k-th smallest rank when full, else 0
trailer: "KMVEND01" | u64 records | u64 sum of (tx ^ m ^ (rk << 32)), wrappingRecord is at byte ; its field m is the sketch’s length, not the
dimension of §10.6. Both counts are lossless from it: the header’s seed and bits
rebuild the permutation, and the running maximum of block is the universe of §10.4.
The commands that were run ($K and $L are lists of --kmv and --l1 specs):
# R1 and R2, concurrently: k = 64, 256, 1024 at seeds 1..16
K=""; for k in 64 256 1024; do for s in $(seq 1 16); do K="$K --kmv $k:seed=$s"; done; done
sketch eval $K --kmv 1024:support=pos --l1 512 --l1 1024 --l1 1024:prec=f64 \
--sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --oracle lastspend-2022.u32 \
--limit 3000000 --every 97 --l1-every 997 --metric-threads 32 --out R1-eval3m --stats < finalBCUTXO_2022.scm
sketch count $K --sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --oracle lastspend-2022.u32 \
--limit 31187785 --every 97 --zstd --out R2-count31m --stats < finalBCUTXO_2022.scm
# R3: the prefix selections from R2's seed-1 stream, one fold with the exact store, then all pairs
# $K: k = 1024 at seeds 1..16, k = 128, 512, 2048 at seeds 1..4
# $L: m = 1024 at seeds 1..8, m = 256, 512 at seeds 1..4
sketch select prefix --counts R2-count31m/counts.kmv-k1024-s1-sets.bin.zst \
--sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --limit 3000000 --out sel
sketch pick --select sel/prefix.txt --config varopt:512 $K --kmv 1024:support=pos $L --l1 1024:prec=f64 \
--exact --oracle lastspend-2022.u32 --limit 3000000 --out R3-pick3m --stats < finalBCUTXO_2022.scm
sketch pairs --in R3-pick3m --out R3-pairs3m --threads 64
# R3b: more seeds on the same selection (k = 1024 seeds 17..64, k = 128, 512, 2048 seeds 5..16),
# no exact fold: pairs reuses R3's exact.bin
# R4: the whole chain
sketch count --kmv 1024 --kmv 1024:seed=2 --kmv 1024:seed=3 --kmv 256 --kmv 1024:support=pos \
--sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --oracle lastspend-2022.u32 \
--limit all --every 4001 --zstd --out R4-countall --stats < finalBCUTXO_2022.scm
# R5 to R7: the whole-chain selections from R4's seed-1 stream, one fold, the production
# varopt sketches of the same records, and all pairs
sketch select chain --counts R4-countall/counts.kmv-k1024-s1-sets.bin.zst --out sel
sketch pick --select sel/chain.txt --kmv 1024 --kmv 1024:seed=2 --kmv 1024:seed=3 \
--l1 1024 --l1 1024:prec=f64 --l1 512:seed=2 --kmv 1024:support=pos \
--oracle lastspend-2022.u32 --limit all --out R5-pickall --stats < finalBCUTXO_2022.scm
# (--long=27 is redundant: as section 9 says, a plain zstd -d reads the production file)
zstd -dc --long=27 < colors.sketch-varopt512.zst | sketch decode --select sel/chain.txt > varopt512.sel.txt
sketch pairs --in R5-pickall --varopt-text varopt512.sel.txt --out R7-pairsall --threads 6410.9 Results on the first 3M and 31.2M records#
Four runs on prefixes of the chain, where exact answers exist, with the binary of §10.8 (139 tests passing):
- R1 (
eval, the first 3M records, every 97th record, 30,928 records): 49 KMV stores ( at 16 seeds each undersets, and underpos) and three L1 stores against the exact store. - R2 (
count, the first 31,187,785 records, all of them): 48 KMV stores ( at 16 seeds) against the exact sizes. - R3 (
pickandpairs, the first 3M records): three selections, made bysketch select prefixfrom R2’s seed-1 stream, with the exact store,varopt:512and L1 stores beside the KMV ones.deep: records with supports of at least 1,024 blocks, one for each of 256 target blocks evenly spaced from the first such record’s block, 44,006, to block 178,609; each target takes such a record of its own block or of the next block that has one (118 moved), and the last target found none left after thewindowhad taken the last deep records: 255 records in blocks 44,006 to 178,081, 32,385 pairs.window: the last 256 such records before record 3M, records 2,999,685 to 2,999,999 in blocks 178,608 to 178,610, 32,640 pairs.even: 1,000 records evenly spaced over the 3M, with no depth condition, 499,500 pairs. R3b added seeds on the same selection, so that has 64 seeds and have 16.
eval and count write their tables as they run: the exactness checks and the count
results below are R1’s kmv-rows.tsv (column set_ok), kmv-seeds.tsv and
l1-summary.tsv, and R2’s count-check.tsv, count-seeds.tsv and count-strata.tsv.
The pair results are read back from R3’s and R3b’s pairs outputs by
sketch pairs-stats, in seconds:
sketch pairs-stats --in R3-pairs3m --out R3-stats # R3's 16 seeds: containment, L1
sketch pairs-stats --in R3-pairs3m --in R3b-pairs3m --out R3all-stats \
--group deep --group window --group even --group deep+even --group deep+even+windowThe second run pools R3b’s seeds with R3’s and gives Table 15
and the paragraph after it (jaccard-seeds.tsv) and panels (a), (b) and (c) of
Figure 10 (jaccard-bins.tsv, jw-bins.tsv); the first gives
the exact whole pairs and the sidenote (errors.tsv), the containment
(containment.tsv), Table 16 and the L1 paragraph
(jw-strata.tsv, l1-precision.tsv), and the numbers of the captions of
Figure 9 and Figure 11 (groups.tsv,
errors.tsv, quantiles.tsv). The Python scripts that first computed these tables
agree with them to the digits they printed: 619 numbers of R3’s analysis, none
different, and the across-seed tables to relative where R3b’s seeds
are read from its f32 matrices. Three even figures need columns that only R3’s
pairs.even.tsv held, which is no longer on disk, and stay the scripts’ own: the
sidenote’s 24.8% and 3.8%, the f32 against f64 difference of
, and the plug-in curve of panel (c).
Within one run every record and every pair shares one permutation (or one projection), so their errors are correlated: within a 10M-record bucket, the error of a count is mostly one offset shared by all its records. A per-run spread across records says nothing about the estimator; seeds are the unit of every bias and variance claim below. A bias test is Student’s over the seeds’ means, Bonferroni-corrected for the strata tested; a variance test compares the mean over records of each record’s variance across seeds with the theory, inside the band that would hold even if all the records of a stratum moved together.
Exactness. In R1 every one of the 49 stores’ 30,928 sampled sketches was compared
with the bottom- of the exact support, ranked by the same permutation: 1,515,472
comparisons, 0 mismatches, and full was set exactly when the support exceeded .
The exact store’s support size equalled the --sets size on all 30,928 records. In R2
every whole sketch had exactly the reference size: 4,615,915, 4,715,656 and 4,792,897
records at , 256 and 1024, for every seed, and no full sketch had a support of
or fewer blocks. The L1 projection matched from the exact colour on 3,010
records with a worst deviation per coordinate, relative to
, of (, f32),
(, f32) and (, f64).
In R3, at every , the pairs whose sketches were both whole had equal to the
exact in every case: 208,335 even pairs at (and 190,653, 205,120 and
209,628 at , 512 and 2048), and 1,953 deep pairs at .
Counts. All 184 seed gates of R2 (92 testable strata, bias and variance) passed, and all 160 of R1. The largest in R2 was 2.08 (, , supports of 8,192 to 16,384 blocks), against Bonferroni thresholds of 4.20 to 4.36; the across-seed variance over theory ran from 0.57 to 1.49, inside bands of about .
| estimator | mean relative error, all full records | RMS, deepest stratum | theory | ratio | ||
|---|---|---|---|---|---|---|
| 64 | 0.56 | 0.0549 | 0.0588 | 0.93 | ||
| 64 | 0.1009 | 0.1151 | 0.88 | |||
| 256 | 1.26 | 0.0269 | 0.0290 | 0.93 | ||
| 256 | 0.29 | 0.0667 | 0.0568 | 1.17 | ||
| 1024 | 0.55 | 0.0152 | 0.0144 | 1.05 | ||
| 1024 | 1.76 | 0.0266 | 0.0283 | 0.94 |
The ratios are those of 16 draws of a stratum that moves as a whole within a run. One seed’s RMS over theory, in a stratum of more than 100,000 records, ranged from 0.22 to 3.08; pooled over 16 seeds, among the strata of more than 100,000 records the ratio left in a few (0.82–0.84 and 1.23 for at , 0.75–0.79 for at ), all inside the variance bands. Panels (a) and (b) of Figure 8 draw the strata of with at least 1,000 records, among them some of fewer than 100,000, where the ratio reaches 1.24 for at (1.22 for ) and 0.78 for at . A per-run accuracy band is not a test, and none is used.
sets. (a) and (b): the
first 31,187,785 records, 16 seeds per , by stratum of (log 2),
strata with at least 1,000 records. (a) RMS relative error pooled over the seeds, with
standard errors across seeds, against the theory RSE of each estimator (lines):
the restricted over (filled markers, solid lines) and
over (hollow, dotted). (b) Mean relative error of , with
standard errors across seeds. (c) R4, all 778,613,440 records, , seed 1, per
10M records: the median (dots) and its 10th and 90th percentiles (thin lines
and band), in thousands of blocks; the exact quantiles (crosses) in the three buckets
wholly inside the first 31.2M records; the median (grey, dotted), the most
an can be. Years along the top. (d) The share of the same buckets’ records
whose sketch is whole and counted exactly, on a log scale. Records of one seed share one permutation, so
their errors are correlated; the spread that counts is across seeds. Drawn from count’s
own tables: R2’s count-strata.tsv and count-seeds.tsv for (a) and (b), R4’s
count-buckets.tsv for (c) and (d), with from R4’s 1-in-4001
count-rows sample.Jaccard similarity. No bias gate failed (0 of 52, groups strata of ). Pooled over seeds, the RMS error matches the hypergeometric SD of Proposition 26, in the table below and in panels (a) and (b) of Figure 10:
| selection | pairs, | (seeds) | largest | threshold | RMS / hypergeometric SD |
|---|---|---|---|---|---|
deep | 31,969 | 128 (16) | 1.08 | 3.73 | 0.93–1.05 |
| 512 (16) | 0.82 | 3.73 | 0.89–1.04 | ||
| 1024 (64) | 2.37 | 3.22 | 0.98–1.03 | ||
| 2048 (16) | 0.99 | 3.73 | 0.93–1.01 | ||
window | 29,749 | 128 (16) | 0.38 | 3.48 | 0.87–1.26 |
| 512 (16) | 2.22 | 3.48 | 0.94–1.29 | ||
| 1024 (64) | 2.21 | 3.05 | 0.83–1.02 | ||
| 2048 (16) | 2.06 | 3.48 | 0.81–0.86 | ||
even | 200,021 | 128 (16) | 1.62 | 3.73 | 0.87–1.12 |
| 512 (16) | 1.79 | 3.73 | 0.87–1.13 | ||
| 1024 (64) | 2.20 | 3.22 | 0.94–1.03 | ||
| 2048 (16) | 1.52 | 3.73 | 0.92–1.02 |
The window is the exception, and it is a small one. Its 256 records have only 110
distinct support sizes, nested within three blocks, so a seed’s error moves almost all
of its pairs together and the per-seed spread is heavy-tailed. Its stratum
came out at a ratio of 0.83 with 64 seeds (ratio squared
); recomputed by brute force from the exact supports with 200 fresh seeds
on 3,000 of its 26,899 pairs (a design-phase computation, not a crate run), the ratio
squared was (in batches of 50
seeds: 1.040, 1.027, 0.700, 1.053). The shortfall in the window (ratios 0.81–0.86
over 16 seeds; ratio squared , and , 1.0
to 3.0 standard errors below 1) reflects the same within-window correlation across
seeds. Within one seed
the fraction of pairs off by more than two hypergeometric SDs was mostly 2–6% per
stratum (extremes 0.7% and 12.5%, both in the window, in its and
strata).The
SE that pairs writes per pair is the plug-in
, which is 0 whenever
is 0 or 1. Against it, 18.5% of the window’s pairs and 24.8% of the even
selection’s were off by more than two SEs (averages over the 16 seeds of R3); among the
pairs with a positive SE, 4.5% of deep, 1.1% of window and 3.8% of even. Coverage
should be judged against the true SD, as above.
Containment of one support in another was defined for every pair of deep and
window, and for 73.1% and 86.4% of the ordered even pairs (older in newer, newer in
older): the undefined ones are small supports against large ones. Across 16 seeds at
no stratum showed a bias ( against a threshold of
3.62); the RMS error per stratum was 0.002 to 0.016 in deep and window, and up to
0.131 in the even pairs whose containment lies in .
Union counts (the restricted universe of the pair) were unbiased in a separate
design-phase check, not a crate run, with 32 seeds on 2.5M records: relative bias
() and RMS over theory 1.01 at on deep pairs.
Figure 9 draws one seed’s for the deep selection
against the exact values.
deep selection: 255 transactions with supports of 1,046 to 123,230 blocks, one
per evenly spaced target block of the first 3M records, in time order; sets,
, seed 1. (a) below the diagonal, the exact above; agreement shows
as mirror symmetry. (b) below the diagonal, clipped at (RMS
0.0102; 1st and 99th percentiles and ; none beyond ). (c) The
strip at the left: of the exact support size, from 3 (dark) to 5.2 (light).
Year ticks where the rows cross 1 January. Errors share one permutation, so they are
correlated across cells (the stripes); the honest spread is across seeds (the Jaccard
table above).Weighted similarity. The L1 store was run at with 8 seeds and at and with 4 each.
| exact | pairs | varopt plug-in | |||
|---|---|---|---|---|---|
| 3,410 | / 0.028 | / 0.024 | / 0.017 | / 0.004 | |
| 2,553 | / 0.031 | / 0.024 | / 0.019 | / 0.023 | |
| 12,230 | / 0.041 | / 0.028 | / 0.021 | / 0.127 | |
| 13,376 | / 0.035 | / 0.025 | / 0.019 | / 0.275 | |
| 1,050 | / 0.026 | / 0.019 | / 0.015 | / 0.434 | |
| 21 | / 0.002 | / 0.001 | / 0.001 | / 0.032 |
On the window’s pairs with (26,677 of them) the L1 store at
has a bias of (SE across seeds 0.0029) and an RMS error of 0.0201, against
0.0263 at and 0.0379 at : the law of §10.6. Below
the mean estimate is the floor (panel (c) of
Figure 10): 0.009–0.011 at , 0.013–0.017 at ,
0.017–0.019 at over the three selections, against 0.0088, 0.0125 and 0.0176
predicted for . f32 and f64 stores gave the same to
relative in the window and in deep; in
even one pair reached , at a TV of (an
absolute difference of ). The plug-in column is §10.2’s bias,
measured. Figure 11 draws the window’s two matrices, the
estimates against the exact values.
sets. (a) RMS of pooled over seeds
(markers, with standard errors) and the hypergeometric SD of §10.5 (lines), in
13 bins of the exact , over the deep and even pairs with at least one full sketch
and (the others are exact); 64 seeds at , 16 at , 512
and 2048. Measured over predicted runs from 0.82 to 1.15 across the bins. (b) The mean of
in the same bins, with standard errors across seeds, in units of
, the four slightly offset; the largest is 2.87
(), against a Bonferroni threshold of 3.54 for 13 bins at a family-wise 0.01 (3.00 at
0.05). (c) The weighted
similarity over the 564,525 pairs of all three selections, in 11 bins of the exact
(the first, , at the left edge): the mean of the L1 store at
and 512 (4 seeds each) and 1024 (8 seeds), with standard errors across
seeds, and the mean plug-in of the production varopt:512 sketches (not used; below
, off the axis, in the first bin). The L1 curves follow the diagonal down to
the floor of §10.6 (mean 0.019, 0.013 and 0.0089 where ); the
plug-in is 4 to 10 times too small for from to 0.7. Errors share one
permutation or projection within a seed, so the honest spread is across seeds.window: the last 256 deep transactions before record 3M (records 2,999,685 to
2,999,999, blocks 178,608 to 178,610), ordered by average-linkage clustering on
with optimal leaf ordering (on the estimate, since production has no exact
values). (a) The set distance on a log scale, sets, seed 1 below
the diagonal, exact above; values of or less, including identical supports
(8.9% of the pairs), take the end colour. (b) on a linear scale to 0.6 (0.45% of
the exact values lie above, counted by the figure script), L1 seed 1 below,
exact above. The strip at the left: of the exact support size, from 4.79
(dark) to 5.10 (light). The two
matrices say different things: nearly the whole history is shared (median 0.994),
while the shared value is a few tenths at most (median 0.18).Cost. Wall times and peak memory are those of /usr/bin/time -v (VmHWM, in GB of
bytes as in §8.9); the busy times and peaks of single stores are each run’s
cost.tsv. R1 took 8 min 24 s and 100.2 GB, almost all of it the exact store. R2 folded
48 KMV stores over 31.2M records in 2 min 55 s and 68.0 GB; a store was busy
146.7 s and peaked at 617,119,725 ranks in 733,466 live sketches. In R3, which folded
the exact store and 29 KMV, 17 L1 and one varopt store in one pass (7 min 36 s,
107.6 GB), a KMV store was busy 11.5 s over the 3M records, an L1 store at
14.3 s and varopt:512 23.9 s; pairs took 56 s for the 564,525 pairs.
10.10 The whole chain#
Counts. R4 counted every one of the 778,613,440 records with five stores in one
pass: at seeds 1, 2 and 3, , and under pos. It took
1 h 09 min 47 s, at 544% of a core, and 144.2 GB (/usr/bin/time -v).
| store | busy | peak ranks | peak live sketches | records cut to |
|---|---|---|---|---|
| , seed 1 | 3,853 s | 7,660,615,688 | 7,593,632 | 137,238,198 |
| , seed 2 | 3,817 s | 7,660,615,688 | 7,593,632 | 135,831,031 |
| , seed 3 | 3,910 s | 7,660,615,688 | 7,593,632 | 135,305,680 |
| , seed 1 | 2,143 s | 1,916,423,324 | 7,593,632 | 102,302,532 |
, seed 1, pos | 3,777 s | 7,660,613,640 | 7,593,630 | 137,238,132 |
At the peak a store holds about 1,009 ranks in each of 7.59M live sketches, as many as the production run of §9 keeps alive: 30.6 GB of ranks.
- Against the exact sizes. On the first 31,187,785 records every hard counter of
every store was 0 (R4’s
count-check.tsv): no whole sketch of the wrong size, no full sketch of a support of at most , no whole sketch of a larger one, no sketch of more than ranks. The whole sketches of exactly the reference size were R2’s: 4,792,897 at , at every seed, and 4,715,656 at . - Determinism. The first 623,755,748 bytes of R4’s seed-1 stream,
, equal R2’s (by
cmp): the whole-chain stream extends the one validated against the exact sizes. - Seeds against each other. Past record 31,187,785 there is no reference, so the
three seeds were compared with each other: per 10M-record bucket and per
pair of seeds, the RMS of the relative difference of their over ,
against the RMS of the records’ theory RSE. Pooled over the 767,323,643 records full
at every seed, the ratio was 0.424 for seeds 1 and 2, 0.966 for 1 and 3, 0.828 for 2
and 3; per bucket it ranged from 0.23 to 1.58. Within a bucket, though, the spread of
the differences around their bucket’s mean is only 0.16 to 0.55 of the theory: most of
a bucket’s seed difference is one offset shared by its 10M records, as one
permutation per seed and heavily overlapping supports make it. The pooled ratios are
therefore a handful of effective draws, not 767M, and should scatter around 1 by a
factor of about 2. Seeds 1 and 2 sit low all along, as on R2, where seed 1 had the
smallest error (RMS over theory 0.37, 0.70 and 0.76 for seeds 1 to 3, in R2’s
count-strata.tsv, and 0.50 for the pair 1–2); without a reference this cannot be told from two close offsets. Reported, not gated. The seed gates of the first 31.2M records passed (0 of 52 failed, in R4’scount-seeds.tsv; with 3 seeds they are weak, a threshold of 36). - Never above the universe. No record has a restricted above (0 of 778,613,440, in each of the five streams), as Proposition 25 guarantees: a check of the decoding.
- Counted exactly. 11,289,797 records, 1.450%, have a whole sketch at ,
and 4,792,897 of them lie in the first 31.2M records. Their supports are small: in a
1-in-4001 sample of the records the median is 2 blocks, the 90th percentile 54 and
the largest 983. Under
posexactly as many sketches are full as undersets. - The file. The seed-1 stream compresses to 1,842,558,077 bytes (
ls), 2.37 B a record, 8.45 times less than its 15,572,268,872 raw bytes; it is the production count file of §10.11.
The comparison of seeds, the check against the universe and the records counted exactly
are read back from R4’s streams by sketch summary (§10.8), with no fold:
R="--range 0:31187785 --range 30187785:31187785 --range 0:100000000 --range 100000000:200000000 \
--range 200000000:300000000 --range 300000000:400000000 --range 400000000:500000000 \
--range 500000000:600000000 --range 600000000:700000000 --range 700000000:"
S=R4-countall/counts.kmv-k1024
sketch summary --in $S-s1-sets.bin.zst --in $S-s2-sets.bin.zst --in $S-s3-sets.bin.zst \
--in R4-countall/counts.kmv-k256-s1-sets.bin.zst --in $S-s1-pos.bin.zst \
--sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --bucket 10000000 $R --out R4-summary
sketch summary --in $S-s1-sets.bin.zst --every 4001 --bucket 10000000 $R --out R4-sampleThe pooled and per-bucket ratios between seeds are R4-summary/dispersion.tsv; the
check against the universe, the records counted exactly and their share are the
over_univ, whole, frac_whole and full columns of summary.tsv, and the
supports of the whole records in the sample its whole_p50, whole_p90 and
whole_max in R4-sample. The first run takes about 5 minutes of wall time. It
replaced a mawk pass over three decoded streams, whose 1,404 per-bucket cells it
reproduces as mawk printed them, and a Python pass over the 1-in-4001 sample, whose
depth table it reproduces up to the rounding of one percentile that falls on a tie.
Panel (c) of Figure 8 follows the counts down the chain. Where
the exact sizes exist, a bucket’s median is within 0.5% of the exact median
(0.9965, 1.0008 and 1.0047 in the first three 10M-record buckets). The median support
grows from 131,000 blocks in the first 10M records to 708,000 in the last 8.6M, and
fills more of its universe as it grows: the median of is 0.85
over the first 100M records and 0.93 over the last 78.6M. The share counted exactly
(panel (d)) is 30% of the first 10M records, 6.1% of the first 100M, and between 0.25% and 1.9% of
every 10M bucket after the first 60M. The finite-population factor shrinks as the
supports fill their universe, so the theory RSE falls with depth: over the full records
its median is 1.21% in the first 100M, 0.92% over the chain (10th and 90th percentiles
0.82% and 1.19%) and 0.81% in the last 78.6M. , over , has a median
RSE of 2.25% over the chain, about 2.5 times that of . These are columns of
R4-summary/summary.tsv: n_p50 against ref_p50 per bucket,
n_p50 alone for the median support, fill_p50, frac_whole, and rse_p10,
rse_p50, rse_p90 and rse_M_p50 over the ranges of the command above. (Its
quantiles are numpy’s linear ones; count’s count-buckets.tsv, drawn in the figure,
takes the lower order statistic, and the two differ in about the sixth digit.)
Matrices. R5 folded the stores of the selected records over the whole chain, and R6
read the production varopt sketches of the same records out of
colors.sketch-varopt512.zst. The selections were drawn from R4’s seed-1 stream by
sketch select chain (§10.8), which prints the ranges below; a record is deep when its
sketch is full, so exactly by
Theorem 22.
w2013andw2017: the first 256 deep records from blocks 240,000 and 470,000 (records 19,031,618 to 19,031,920 in blocks 240,000 to 240,002, and records 229,491,548 to 229,491,813, all in block 470,000).w2022: the last 256 deep records of the chain, which are its last 256 records, all in block 762,260.chain: 512 target blocks evenly spaced from 50,000 to 762,260; each takes a deep record not already selected, from the first block at or after the target that has one (40 picks moved past their target). All 512 targets found a record: records 51,126 to 778,611,720, in blocks 50,299 to 762,260, with from 1,254 to 711,490 (median 354,641).- R5 folded seven stores, four KMV ( at seeds 1, 2 and 3, and seed 1 under
pos) and three L1 ( at seed 1 inf32and inf64, at seed 2), over all 778,613,440 records, and dumped the 1,280 selected: 1 h 10 min 05 s at 607% of a core, and 249.8 GB (/usr/bin/time -v), 0.6% below the 251.2 GB that a memory model fitted to R4, outside the crate, predicted (chain.log prints 242.2 GB: its run-time check compared R4’s VmHWM in GiB with the model in GB and so left the model unscaled). A KMV store was busy 3,872 to 3,969 s and reproduced R4’s peaks and counts of cut records exactly; the L1 stores were busy 2,667 s (,f32), 3,374 s (f64) and 2,348 s (), in R5’scost.tsv. - R6 cut the 1,280 records out of the production file, beside R5.
- R7 computed the 228,736 pairs (130,816 in
chain, 32,640 in each window) in 3.84 s and 0.2 GB (/usr/bin/time -v).
The checks on these pairs were first made by a Python script, r7_checks.py. The crate
now makes them from R7’s output, with the same results to the six digits the script
printed (at worst relative): the first two by pairs-stats
(seed-agreement.tsv, seed-pairs.tsv, l1-precision.tsv), the fourth by running
pairs again with the binned colours of the selected records (bands-check.tsv), in
seconds and without a fold:
sketch pairs-stats --in R7-pairsall --out R7-stats
sketch pairs --in R5-pickall --varopt-text varopt512.sel.txt --bands bands1024.sel.txt \
--out R7-bands --threads 32The checks:
across seeds 1, 2 and 3. For each cell, is the standard deviation of the three seeds’ and the hypergeometric SD of Proposition 26 at their mean and union count. If the estimates were independent and normal, would be distributed as : mean 1, and with probability . The gate, a mean in , passed in every group: 0.933 in
chain, 0.876 inw2013, 1.154 inw2017, 1.134 inw2022. The share of cells with , among those with and at least 10, is reported, not gated: 0.976, 0.991, 0.963 and 0.699. The low one is a single offset: inw2022the difference between seeds 1 and 2 has mean and a mean of 3.73, against 0.99 and 1.50 for the other two pairs of seeds. Its 32,640 cells share one permutation per seed, so one unlucky pair of permutations moves them all. No pair in these groups has two whole sketches, so no cell is exact.L1 in
f32againstf64. The two gave the same to relative at worst (inw2013; inchain), with a 99th percentile of at most in every group, and a pair at 0 inf64was 0 inf32: below the that the check allows. The figures usef64all the same.L1 against the exact could not be checked at full depth. It needs pairs whose two
varoptsketches are unreduced, and so are the colours, up tof32; every selected record has more than 1,024 blocks, so itsvaropt:512sketch is always reduced. The check stands on the prefix (§10.9).L1 against an exact lower bound. Binning two colours into the same 1,024 bands can only lower their TV, and
colors.bands1024.zstholds every record’s exact binned colour; soshould hold in at least 99% of the pairs. Read for the 1,280 selected records into
bands1024.sel.txt(a separate Python andmawkpass over the 1.67 TB file, 3 h 42 min of wall time;pick --bands-refnow copies the same lines during the fold, which R5 predates), it holds in 99.985% of the 130,816chainpairs at , in 100%, 99.97% and 99.997% of the 32,640 pairs ofw2013,w2017andw2022, and likewise at and inf64; every band line’s transaction matched the selection. The bound is far from tight inside a window: the median of (over pairs with , at ) is 1.10 inchainbut 1.36 to 1.82 in the windows, whose colours differ mostly within bands of 745 blocks. A check that passes, then, and not an exact reference.
Across time, in the whole-chain matrix of Figure 12, the upper
triangle has no exact to show, as the prefix’s has, and a containment drawn on
would be a flat field. On the prefix deep pairs, the containment of the older
support in the newer is exactly 1 in 81.6% of the cells and at least 0.9 in 90.9%, and
the share of cells at 1 grows with the gap: 41% under 5,000 blocks apart, 63% at
5,000–20,000, 86% at 20,000–60,000 and 97% beyond. For nested pairs is just the
ratio of the two sizes, which the strip already shows. What is
informative is the 18.4% of cells that are not nested (5,968 of 32,385), whose
spreads from (p10) through (p50) to (p90), and
the KMV estimate tracks the exact value there (721 cells fall below the resolution of
). So the upper triangle of the whole-chain matrix shows
, clipped to : its
floor colour means “nested, to the resolution of ”.
Over the whole chain the field is flatter still. The containment is defined in 129,791
of the 130,816 cells of chain, and 98.5% of those are at the floor (
exactly); only 1,970 cells, 1.5%, are not nested to the resolution of , with
at , and (p10, p50, p90), and 316 of them
in one row: record 102,455, of block 73,701, with 1,623 blocks, whose median containment
in the later supports is 0.917. The containment is undefined in 1,025 cells (0.78%):
small early supports (1,250 to 2,400 blocks, in blocks 75,115 to 116,905) against late
ones (from block 554,576), where no sampled element of the older support ranks below
the newer one’s threshold. The fallback is 0 in all of them,
since is, and 0 would read as “disjoint”, so they are drawn hatched instead.
has percentiles 0.016, 0.48 and 0.89 (p10, p50, p90), and its median by block
gap tracks the ratio of the smaller count to the larger (0.989 against 0.990 under
5,000 blocks apart, 0.413 against 0.412 beyond 60,000): nested pairs, as the
containment says.
chain selection: 512 deep transactions, one per evenly spaced target block from
block 50,000 to the end of the chain, in time order (blocks 50,299 to 762,260); sets,
, seed 1. (a) Below the diagonal, . Above it,
for the containment of the older support in the newer,
clipped to : the floor colour, or less, means nested to the resolution of
(98.5% of the defined cells); grey and hatched, undefined (1,025 cells): no sampled
element of the older support ranks below the newer one’s threshold. The strip at the
left: , from 3 (dark) to 6 (light). (b) between the production
varopt:512 sketches of the same records, read out of the production file without a
new fold, in years of 144 blocks a day, on a log scale clipped to . Year
ticks, every other year, where the rows cross 1 January. is not drawn; its
quantiles are in the text. Errors share one permutation, so they are correlated across
cells; the honest spread is across seeds., the “temporal distance”, has percentiles 0.48, 1.86 and 4.26 years (p10, p50,
p90), and a Spearman correlation of 0.82 with the gap in blocks and of 0.77 with
. The weighted similarity is far from the floor across the whole chain, unlike
on the prefix: L1 (, f64) has percentiles 0, 0.21 and 0.59 (p10,
p50, p90), only 20.5% of the pairs lie below the floor of 0.0088, and its median falls
with the gap from 0.55 under 5,000 blocks to 0.18 beyond 60,000. The independent store
at , seed 2, agrees (median 0.18, p90 0.59). On the prefix, deep pairs across
time had a median of (§10.1): what holds for the first 3M
records does not hold for the chain as a whole.
Inside a window, where is close to 1, the weighted similarity is what tells transactions apart, and the three windows differ (Figure 13):
sets, , seed 1, on a log
scale; or less, identical sketches included, takes the end colour. Bottom:
from L1, , seed 1, f64, on .In all three the median is , two sampled elements apart, and
in 21.9%, 32.4% and 36.9% of the pairs. The weighted similarity rises from
era to era: has percentiles 0.11, 0.44 and 0.72 (p10, p50, p90) in 2013,
0.40, 0.75 and 0.85 in 2017, and 0.58, 0.78 and 0.87 in 2022, below the floor in 2.7%,
1.6% and 0.02% (5 pairs) of the pairs. The median between two transactions of a
window is 0.19, 0.25 and 0.35 years. Under pos, every of the four groups
equals the sets one.
The numbers given since the checks, in the text and in the captions, are tables of
pairs-stats: of R3-stats for the prefix’s deep pairs, of R7-stats for the
whole chain. The percentiles, the
shares at 1, at the floor and below the L1 floor, and their split by block gap are in
quantiles.tsv; the row of record 102,455 and the undefined cells in cont-rows.tsv;
the Spearman correlations in spearman.tsv; pos against sets in support.tsv.
10.11 The production count file#
colors.kmv1024.counts.zst, 1,842,558,077 bytes (SHA-256
c8d38950e06278e86b4affc86f1906bbb59712746aba29d2e1d9fce9485a7a7d), is R4’s seed-1
stream, copied after R4’s checks passed. It is one zstd frame with a 4 MiB window, so
a plain zstd -d reads it.
It holds, for each of the 778,613,440 transactions in record order, the 20-byte record of
§10.8 for the , seed-1, sets sketch of its support. Read it with
zstd -dc colors.kmv1024.counts.zst | sketch decodewhich verifies the trailer and writes a comment line naming the stream
(# kmv-k1024-s1-sets k=1024 seed=1 support=sets bits=20 M=1048576) and then
rec tx block univ full m n_hat se n_hat_M se_M, one line a record. Or read the raw
records with numpy, dtype [('tx','<u8'),('block','<u4'),('m','<u4'),('rk','<u4')] at
offset 48 with count = (size - 48 - 24) // 20 (the last 24 bytes are the trailer):
then m & 0x7fffffff is the sketch’s length, bit 31 says full, and
follows directly, while the restricted
needs the permutation, which decode rebuilds from the header.
What an means: when full is clear (every support of at most 1024 blocks, 1.45%
of the records) it is , the number of blocks the transaction
descends from, through zero-amount inputs too. Otherwise it is an exactly unbiased
estimate with a standard error of about
blocks, written as se (and as
se_M for , with in place of ). The relative error
se / n_hat has a median of 0.92% over the chain, 1.2% over its first 100M records and
0.8% over its last 78.6M. These figures, and the 1.45%, are what sketch summary writes
for the file itself, the same as for R4’s stream, of which it is a byte copy (cmp):
sketch summary --in colors.kmv1024.counts.zst \
--sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --bucket 10000000 $R --out prod-summarywith the ranges $R of §10.10; it reads the 778,613,440 records in about 3.5 minutes of
wall time. All records share one permutation, so their errors are correlated, by
design: two records
with nearly the same support get nearly the same error. A second seed’s file is the
way to an independent estimate; R4 computed seeds 2 and 3, which are not shipped.
11. Ten Sketched Colours#
What the production file holds, read for a few transactions: the sketch of
§5.5, a polynomial in with at most 512 terms, where the exponent is the block a coin
was minted in and the coefficient the sketch’s estimate of the share of ’s value
minted there. The ten below are among the 1,280 records of §10.10 that R6 cut out of
colors.sketch-varopt512.zst, each picked for one property of its sketch. Each has
exactly 512 terms, and its coefficients sum to 1 to seven digits, as point 4 of
Theorem 3 and Theorem 7 say they must. The
subscript is the record number.
Terms with equal coefficients are grouped, heaviest group first, and only the first
four groups are written out; is the rest, its mass. The
coefficients are rounded to six digits. All 5,120 terms, as stored, are in
ten-colours.txt.
All of this section is read by sketch describe. It takes the 1,280 sketches as
sketch decode --select prints them, their exact colours binned in the 1,024 bands (the
lines of colors.bands1024.zst read for the check of §10.10) and their . It
writes a row per record to describe.tsv, with the columns of
Table 18 and a few more, and totals over the 1,280 to
summary.tsv; for the records given by --records, also the table’s rows (table.md),
the displays below (displays.md) and ten-colours.txt (colours.txt). The Python
scripts that did this first gave the same rows and displays, and the same band
comparisons to the bit. Several of the ten are extremes of one column of describe.tsv:
the second has the largest coefficient, the sixth the most distinct ones, the seventh
the smallest age, the tenth the largest .
# the 1,280 records of §10.9's selection: their sketches (R6) and their counts
zstd -dc --long=27 < colors.sketch-varopt512.zst \
| sketch decode --select sel/chain.txt > varopt512.sel.txt
zstd -dc colors.kmv1024.counts.zst | sketch decode --select sel/chain.txt > counts.sel.tsv
TEN=51126,99576,243275,456104,19031745,69818050,77146563,229491784,778613383,778611720
sketch describe --in varopt512.sel.txt --bands bands1024.sel.txt --counts counts.sel.tsv \
--select sel/chain.txt --records $TEN --out describe| record | block | group | distinct coefficients | heavy entries | largest coefficient | mean block | newest block | KS | (blocks) | |
|---|---|---|---|---|---|---|---|---|---|---|
| 51,126 | 50,299 | chain | 8 | 263 | 0.0150 at each of 16 | 39,923 | 47,918 | 1,506 | 0 | |
| 99,576 | 72,310 | chain | 26 | 109 | 0.9942 at 71,925 | 71,906 | 71,925 | 2,267 | 0 | |
| 243,275 | 104,360 | chain | 33 | 352 | 0.9500 at 99,535 | 98,783 | 102,880 | 20,742 | 0 | |
| 456,104 | 121,087 | chain | 54 | 285 | 0.0083 at each of 2 | 66,631 | 93,271 | 16,532 | 0.00028 | 10 |
| 19,031,745 | 240,001 | w2013 | 107 | 113 | 0.9093 at 239,070 | 236,737 | 239,070 | 190,919 | 6 | |
| 69,818,050 | 358,042 | chain | 437 | 439 | 0.0100 at 357,814 | 357,545 | 357,937 | 310,142 | 2 | |
| 77,146,563 | 366,405 | chain | 308 | 321 | 0.0337 at 366,190 | 366,128 | 366,271 | 320,370 | 0 | |
| 229,491,784 | 470,000 | w2017 | 35 | 48 | 0.0501 at 210,595 | 165,048 | 229,223 | 183,586 | 0.0016 | 142 |
| 778,613,383 | 762,260 | w2022 | 1 | 0 | at each of 512 | 175,122 | 391,528 | 443,316 | 0.0025 | 262 |
| 778,611,720 | 762,260 | chain | 1 | 0 | at each of 512 | 351,468 | 761,472 | 711,490 | 0.0025 | 524 |
The ten, in the order of the table:
- The first
chainrecord. It is the first deep record at or after block 50,000; the first deep record of the chain is earlier, record 44,447 in block 44,006, assketch select chainreports when it makes the selection. Its 512 terms take only 8 values: whole groups of blocks reach it along the same paths through the DAG, so they share one product of shares. The four groups shown, 222 terms, are all above , which no reduction’s can exceed (Lemma 2), so every reduction on the way kept them as they came. Of the 290 terms in , 41 are heavy too, and the other 249 are the lights of this record’s own last reduction, all equal to its .
- The most concentrated colour. One block, minted 385 blocks earlier, carries 99.42% of the value. Binned, the exact colour puts 0.9949 in that block’s band (blocks 71,520 to 72,264), and so does the sketch.
- One block and a long tail. 95% from block 99,535, and a tail that reaches back to block 9.
- Old money in 2011. A diffuse colour, with no coefficient above 0.84%, whose heaviest terms are blocks of early 2009.
- The 2013 window. 91% of the value was minted in one block, 931 blocks earlier.
- The richest structure. 437 distinct coefficients out of 512: the sketch is mostly heavy entries (439), which the last reduction kept with their own weights. Its top band (blocks 357,600 to 358,344) holds 0.5665 of the value, in the sketch and in the exact colour.
- The youngest money of a deep colour. The sketch’s mean block is only 277 blocks before the transaction’s own, though its support is about 320,000 blocks: 99.58% of the value was minted in blocks 365,795 to 366,539, and the sketch puts the same 99.58% there.
- The 2017 window, spending 2013 coins. In block 470,000, mid-2017, the newest block of the sketch is 229,223, from spring 2013; and the exact colour agrees at the bands’ resolution: none of its value was minted after block 229,459.
- Pre-2016 money in 2022: a flat sketch. In the last block of the data, the sketch’s newest block is 391,528, from early January 2016. The exact colour is not quite so old: 0.051% of its value was minted after that block’s band, as late as blocks 495,425 to 496,169, in late 2017. Together those shares are about a quarter of ; a light entry is kept with probability , and the sketch kept none of them. That is VarOpt sampling, not an error: in expectation they are there.
- The largest support. About 711,490 distinct blocks, 93% of the 762,261 that existed then, also as a flat sketch. Its 512 blocks are a sample of the whole chain: binned, it puts mass in 498 of the 1,023 bands where the colour has some, and its total variation distance from the binned colour is 0.42, yet at every one of the 1,024 band edges its CDF is within 0.0026 of the exact one (band-edge KS 0.00254), and its is 524 blocks, under four days.
Flat sketches. 543 of the 1,280 sketches of §10.10 are flat (flat in
summary.tsv), as 9 and 10 are: 512
coefficients all equal to . A sketch is flat when no entry of the merged parents'
sketch exceeds the threshold of the last reduction
(Definition 1). Every entry is then light, each is kept with
probability , and every kept one gets ; the mass is 1 and exactly
entries are kept, so . A flat sketch is thus an equal-weight sample of
512 blocks, each drawn with probability proportional to its weight in the merged
sketch, and is unbiased like any other.
Read with care. Each coefficient estimates the share of one block without bias (Theorem 7), but the estimate of a single light block is crude: it is or 0. What a sketch gets right is the colour’s CDF, and the functionals of §5.1. The KS column of the table, against the binned exact colour, runs from , for colours made of heavy entries, to for the flat sketches, a little over . That is allowed: the bound of Corollary 4 is for one reduction against its own input, and through the recurrence the errors of the earlier reductions add to it (§6.3).
12. The Colour Surface#
A colour is a probability distribution over the blocks (§5.1), and so is its sketch: the coefficients are nonnegative and sum to one (point 4 of Theorem 3). Set side by side in the order of the chain, the 778 million sketches make a surface over two time axes. One axis is the block a transaction is in, when its coins are spent. The other is the block they were minted in. The height is the share of the transaction’s colour minted there. This section draws that surface for the whole chain and reads it.
Too many transactions share a block for the surface to be drawn one transaction at a
time, so it is drawn as an average. With band of 745 blocks (the 1,024 bands
of colors.bands1024.zst) and the transactions in the blocks of band , less the
coinbases,
with the coefficient of in the production sketch of . Each column is a probability distribution over minting bands. By Theorem 7 and linearity it is an unbiased estimate of , the same average of the exact colours. Its error does not shrink like , though. The transactions of one band share ancestors, and the sketch of an ancestor was reduced once and then handed down to all of them, so their errors are correlated. §12.6 measures the error against the exact colours.
Three things the average is not:
- It is not weighted by value. Each transaction counts once, whatever it moves, so a column is the colour of a transaction drawn at random from its band, not the colour of the bitcoin that moved in it. Value weights need the transactions’ amounts, which neither the sketch file nor the count file holds.
- “Minted in ” means paid out by the coinbase of block , fees included, as in §5.1: a coinbase has the colour whatever part of it is fees.
- The age is the time since minting, measured through every transaction since the coinbase. It is not the time since the coins last moved, which is what the coin-age charts of chain analytics (HODL waves, coin days destroyed) measure.
12.1 How it was computed#
Two modes of the crate compute this section. sketch surface reads the files once and
writes a surface as sums, by minting band and by age band (<prefix>.mint.f64,
<prefix>.age.f64), the transactions of each row (<prefix>.rows.f64) and its
counters (<prefix>.surface.tsv). sketch surface-report turns a sketched and an exact
surface into the tables and numbers of §12.2 to §12.6 and the series the figures draw,
with the calendar from a file of each year’s first block.
- The sketched surface.
sketch surfacereads the production filecolors.sketch-varopt512.zston its input and, beside it, the count file of §10.11 for each record’s block. It skips the first record of each block, the coinbase, and adds every other sketch, divided by its mass, to the row of its band. A coefficient at a block later than its transaction’s own would mean that the two files do not line up, and the mode fails on one. - The exact surface. With
--bands-ref, the same mode reads the exact colours ofcolors.bands1024.zst, already binned in the same bands, parses the text on--threadsand adds the lines in record order, so the sums do not depend on the number of threads.
zstd -dc --long=27 < colors.sketch-varopt512.zst \
| sketch surface --counts colors.kmv1024.counts.zst --out all
sketch surface --counts colors.kmv1024.counts.zst --bands-ref colors.bands1024.zst \
--threads 16 --out xall
sketch surface-report --sketched all --exact xall --years years.tsv --out reportThe whole-chain surfaces all and xall were computed before these modes existed, by
two small Rust programs outside the crate that do the same: surface-aggb, through a
copy of the crate’s decoder, and surface-aggxp, with 16 threads parsing the text.
surface-aggb read 778,613,440 records, skipped 762,261 coinbases and kept 777,851,179,
in 2 h 00 min and 7 MB of memory; surface-aggxp took 4 h 22 min and 0.2 GB, with
zstd’s single-threaded decompression as the limit (wall times and peak memory from
/usr/bin/time). Both runs kept the same records in every row, and no coefficient sat
at a block later than its transaction’s own. sketch surface gives the matrices of
surface-aggb bit for bit on the first 3M and 30M records, and on the first 30M those
of the single-threaded first version of surface-aggxp; the 16-thread version added in
the order its threads finished, and differs from them by at most
relative. sketch surface-report, run on the whole-chain all and xall, reproduces
every table and number of §12.2 to §12.6, to the last digit of the Python scripts that
first computed them, and refuses two surfaces whose rows differ. As a cross-check of the
reader, on the first 3M records a version that reads the text of sketch decode agreed
with the sketched surface to in the averaged surface (
in the raw sums).
The figures are drawn by a Python script outside the crate, from the two surfaces; the
report’s surface-age-cdf.tsv, surface-columns.tsv and surface-ratio-curves.tsv
hold the series of Figure 16,
Figure 18(a) and Figure 17,
equal to the script’s to the bit.
12.2 The surface#
Figure 14 reads from left to right.
- Before 2012, what is spent was just minted. The mass sits on the diagonal. Of the colour of a transaction of 2011, 59% was minted in the week before and 92% in the year before.
- Then the mass spreads over the whole past. From 2012 each column covers nearly the whole triangle below the diagonal, at between and per band. By 2022 the median age is 8.1 years, and three quarters of the colour is older than four years (§12.4).
- The halvings are horizontal steps, at minting blocks 210,000 (November 2012), 420,000 (July 2016) and 630,000 (May 2020). A block after a halving mints half as much, so it is half as large a share of everything that mixes it in. In (b), the same steps run along diagonals.
- The coins of 2009 and early 2010 stay pale along the bottom of (a), all the way to 2022. They are spent far less often than their share of the supply (§12.5).
- Dark patches in 2010 and 2011 are single holdings moving, such as the coins minted around blocks 20,000 to 35,000 and spent in late 2010. With few transactions per band in those years, one large holding is visible on its own.
The shares of 2011 and 2022 are rows of Table 19, and
surface-check.tsv holds the checks behind the second and third readings: from 2012 on
every cell below the diagonal is above zero, 99.3% of them between and
, and in the colour of 2022 the ten bands before each halving carry 1.94 to
1.97 times the share of the ten after it.
12.3 In three dimensions#
The same numbers as a height (Figure 15) show the shape at a glance: a ridge along the diagonal in the first years, then a plateau that falls slowly with age. The rest is hard to read. The near side hides the far one, the perspective changes how high things look, and no value can be read off. The halving steps, clear in Figure 14, are hard to find. The rest of the section reads the surface from the heatmap and from its slices; the 3D view is better suited to exploring the surface interactively than to a page.
12.4 The age of the coins that move#
| year spent | transactions | mean age | median age | under a week | under a year | over 4 years |
|---|---|---|---|---|---|---|
| 2010 | 117,811 | 0.29 | 0.16 | 22.0% | 91.9% | 0.0% |
| 2011 | 1,845,990 | 0.19 | 0.01 | 58.8% | 92.1% | 0.0% |
| 2012 | 8,393,844 | 0.75 | 0.35 | 18.7% | 72.0% | 0.0% |
| 2013 | 19,550,074 | 1.39 | 1.11 | 9.3% | 47.0% | 3.8% |
| 2014 | 25,171,092 | 1.79 | 1.36 | 7.7% | 45.2% | 13.6% |
| 2015 | 45,625,103 | 2.17 | 1.47 | 4.5% | 42.7% | 22.7% |
| 2016 | 82,934,251 | 2.83 | 2.23 | 2.8% | 32.0% | 34.5% |
| 2017 | 103,963,956 | 3.94 | 3.82 | 1.7% | 17.8% | 48.4% |
| 2018 | 81,173,269 | 4.61 | 4.75 | 2.6% | 19.2% | 56.2% |
| 2019 | 119,946,976 | 4.88 | 4.91 | 2.4% | 22.0% | 57.1% |
| 2020 | 111,939,087 | 5.62 | 5.78 | 1.5% | 17.0% | 63.3% |
| 2021 | 98,075,965 | 6.81 | 7.28 | 1.3% | 9.9% | 72.4% |
| 2022 | 79,113,540 | 7.42 | 8.12 | 1.5% | 12.0% | 74.6% |
- Coins get older. The median age rose from 1.1 years in 2013 to 8.1 in 2022, when the chain was 13 years old. The rise was uneven: fastest from 2016 to 2017 and from 2020 to 2021 (+1.6 and +1.5 years), slowest from 2014 to 2015 and from 2018 to 2019 (+0.11 and +0.16).
- Young coins don’t disappear. The share under a week old falls from 59% in 2011 to 1.3–2.6% from 2017 on, and the share under a year old falls to 10–22%. Since 2018 the mean has been below the median: the young part is small but pulls the mean down.
- The jump at the turn of 2018 in (b), where the median moves from about 4 to 5 years within weeks, coincides with the rise and fall of the price in December 2017 and January 2018. The coins spent then were older than in the months around them.
12.5 What moves against what exists#
Coins of every age exist, in known amounts: block mints a subsidy of BTC. If the coins that move were a fair draw from the coins that exist, the colours of a year would put on each minting band its share of the supply. Figure 17 divides the one by the other.
| year spent | minted before 2010: colour / supply | before 2011 | before block 210,000 | minted in the year before |
|---|---|---|---|---|
| 2012 | 8.4% / 20.1% | 38.2% / 62.6% | 100.0% / 100.0% | 61.8% / 37.4% |
| 2013 | 4.2% / 15.1% | 23.0% / 47.0% | 96.3% / 98.6% | 46.2% / 24.9% |
| 2014 | 3.6% / 13.1% | 21.9% / 40.9% | 69.7% / 85.8% | 28.6% / 13.0% |
| 2015 | 3.0% / 11.7% | 17.1% / 36.5% | 51.8% / 76.6% | 31.6% / 10.8% |
| 2016 | 2.6% / 10.7% | 14.9% / 33.2% | 44.2% / 69.7% | 26.8% / 9.0% |
| 2017 | 2.7% / 10.0% | 16.0% / 31.1% | 45.2% / 65.1% | 15.2% / 6.5% |
| 2018 | 2.8% / 9.6% | 16.5% / 29.8% | 46.8% / 62.4% | 10.3% / 4.2% |
| 2019 | 2.6% / 9.2% | 14.7% / 28.6% | 41.8% / 60.0% | 13.0% / 3.9% |
| 2020 | 2.3% / 8.8% | 13.3% / 27.5% | 38.2% / 57.7% | 12.7% / 3.8% |
| 2021 | 2.3% / 8.6% | 13.9% / 26.9% | 39.6% / 56.3% | 5.8% / 2.5% |
| 2022 | 2.3% / 8.5% | 13.8% / 26.4% | 39.3% / 55.3% | 5.9% / 1.7% |
The curves have three parts, and those of 2018, 2020 and 2022 lie almost on top of each other up to 2017:
- The first year is spent least. In the colours of every year from 2013 on, coins minted in 2009 get about a quarter of their share of the supply (0.24 to 0.30 of it), and the oldest bands less than that. In 2022, coins minted before 2010 are 8.5% of the supply but 2.3% of a transaction’s colour. A coin enters a colour only once it moves, and many of the earliest coins never have: lost keys, or coins held since the first year, among them those of the earliest miners.
- The middle is well mixed. Coins minted from 2012 to about two years before the year spent sit near their share, between about 0.8 and 2 times it.
- The last months are spent most. The coins of the last month before the year get 2.8 to 6.2 times their share, and the curves rise toward it over the year before. In 2022, the coins minted in the year before, 2021, are 1.7% of the supply and 5.9% of a transaction’s colour. New coins pass through exchanges and payments before they come to rest.
The ratios are columns of surface-ratio.tsv too: ratio_before_2010 for the first
year, the mixed_* spread of the bands in the middle, and ratio_last6 for the last
month.
The comparison is between two different things: the supply counts bitcoin, and the colour is averaged over transactions. A value-weighted surface would compare like with like, and would need the amounts (§14).
12.6 Sketched against exact#
colors.bands1024.zst. (a) The total
variation distance between each sketched column and the exact column. (b) The difference
per cell, on a symmetric log scale (linear below ).The two surfaces were computed from the same 777,851,179 transactions, row for row, so
any difference comes from the sketches. The numbers below are in surface-check.tsv,
with the medians by year in surface-tv-years.tsv and the ages read from bands in the
sketched-bands and exact-bands rows of surface-age.tsv; the 0.42 of a single
sketch is from §11’s describe.tsv.
- Columns. The total variation distance between a sketched column and the exact one is at most 0.0029 before 2011 and at most 0.010 in 2011, with few transactions and small colours. From 2012 on, where every column averages at least 27,512 sketches, it is between 0.006 and 0.040, and it grows slowly with time: the median column is at 0.013 in 2013 and at 0.034 in 2022. A single sketch is much further from its binned colour: 0.42 for the tenth sketch of §11.
- Cells. No cell differs by more than , and 99% of the cells where the exact surface is not zero differ by less than .
- Ages. Read the same way from both surfaces, as differences of bands, the mean age of a column is within 0.0028 years (one day) of the exact one in every column. The median is within 0.0044 years from 2012 on, and within 0.00014 years before, except in one 2009 column of two transactions. There the colour’s cumulative share is exactly one half over three empty bands, so the median is not unique and the two surfaces settle on ends 0.042 years (three bands) apart, although the columns themselves agree to within . The shares of Table 19 read from both surfaces this way agree to three decimal places, and so do the 2009 colour shares behind Table 20. Divided by the supply share, they give a ratio of 0.273 sketched against 0.275 exact in 2022. (The table itself reads ages from the blocks of the sketches’ terms, which the exact file, binned, cannot give. Read from band differences, “under a week” is smaller, 44.8% against 58.8% in 2011: a coin minted at the end of a band and spent at the start of the next is one band old, however few blocks apart the two are.)
The errors do not cancel as they would if the sketches were independent. Figure 18(b) is striped along the spending axis: a minting band that a column overstates tends to be overstated in the columns after it too. That is what inherited sampling decisions do. When a reduction keeps or drops a light block for some transaction, every later transaction that spends those coins inherits the choice (§6.3). The surface is accurate to a few parts in a thousand for the questions of §12.4 and §12.5, which sum many cells. It is less accurate for a single cell, where the error can be a sizable fraction of the value.
13. Pictures of the Exact Colours#
Below the wall of §5.3 the exact fold of §5.1 still runs, and the
main binary draws what it computes. Section 12 averaged sketches over the whole chain;
this section draws the head of the chain exactly, record by record, with nothing averaged
and nothing sketched. Every picture here is made by coloring-bt-transactions, not by
sketch.
13.1 One pixel per transaction and block#
--png draws a row per record and a column per block id, each pixel saying what the
colour says about that block: one bit under the unweighted backends --rings and
--sets, eight under --weighted. --pdf (in a build with --features pdf) and
--fold fold that onto a bounded canvas, shading each cell by how much of its rectangle
is inked.
--palette reads the weighted samples through the colour ramp of §13.3 instead of as
greys. The image data are byte for byte those of the greyscale run; the file grows by
780 bytes, a PLTE chunk of 256 colours and its header (the main binary’s
documentation, src/main.rs). What the ramp buys is levels:
grey has 254 and an eye reads perhaps thirty, and these weights live in a fraction of a
percent.
13.2 The first million, exactly#
Figure 19 to
Figure 22 are four --fold pages over the head of
the 2022 chain, two readings of each of two spans. The readings are the support, under
--sets, and the colour of (1), under --weighted;
§5.1 says why the two share their blocks and differ only in the coefficients. The spans
are the 1,000,001 records the driver stops at by default, and 1,024 records, at one row a
record, around the Mt.Gox proof-of-reserves. Nothing in them is a projection or a sketch:
every cell is drawn from whole colours, each kept until its transaction’s last output is
spent, the census rule of §5.3, with no release oracle.
Each page is one greyscale canvas, with no --palette: at most
cells, each shaded by its coverage through the gamma that the driver fixes as
TONE in src/image.rs, which lifts sparse ink and keeps its order. The four canvases
come from four runs over the records (the script make_provenance_figures.sh of the main
binary’s write-up):
coloring-bt-transactions 1000001 --sets --fold history_sets.png < finalBCUTXO_2022.scm
coloring-bt-transactions 1000001 --weighted --gain 1000 --fold history_weighted.png < finalBCUTXO_2022.scm
coloring-bt-transactions --sets --rows 830362..831386 --fold window_sets.png < finalBCUTXO_2022.scm
coloring-bt-transactions --weighted --rows 830362..831386 --gain 2000 --fold window_weighted.png < finalBCUTXO_2022.scmfigs_exact.py, a script outside the crate, adds only the axes and, on the two window
pages, the blue marker, and embeds every canvas cell as one image pixel. Timed one at a
time under /usr/bin/time -v, at a load average of 3, the support of the history takes
74.5 s and 5.36 GiB, and its weighted page 86.0 s and 16.78 GiB, most of it the 15.2 GB
(14.2 GiB) of distinct terms that Table 1 counts at a million
records; the two windows take 25.9 s and 25.3 s. These times are quoted from a comment
in that script; no log was kept.
A weighted page drawn plainly is near white, because the ink in it genuinely is. Each
weighted run therefore declares a --gain, 1000 over the history and 2000 over the
window, and its caption quotes it. The gain lifts ink before the gamma and full coverage
caps it, so these shades order cells and do not measure them.
coloring-bt-transactions 1000001 --sets --fold history_sets.png < finalBCUTXO_2022.scm;
page drawn by figs_exact.py (§13.2).--weighted --gain 1000: the colour of
(1) rather than its support, on the cells of
Figure 19 (about 977 records by 133 block ids, gamma
). The declared gain lifts every cell’s ink before the gamma, so shades order
cells but do not measure them. Value concentrates along the frontier, because coins
mostly move soon after they are minted, and the deep history that dominates the support
carries almost none of it. Main binary:
coloring-bt-transactions 1000001 --weighted --gain 1000 --fold history_weighted.png < finalBCUTXO_2022.scm.The two pages read together. The 95.6% of Figure 19
counts the cells left of the running maximum of each row’s rightmost inked column, as
figs_exact.py computes from the canvas. The weighted page is the exact,
record-by-record form of the first reading of §12.2, “before 2012, what is spent was
just minted”: the value sits in a dark rim along the frontier. Side by side, the pages are
the contrast of §10.1 between and : old supports are shared, while a colour’s
weight sits on its recent blocks.
--rows draws a window and still colours everything in front of it: the 1,024 rows of
Figure 21 and
Figure 22 inherit from all 830,362 records before
them, folded and not drawn. The row axis is the record ordinal, not the transaction id
(the two BIP-30 duplicates of §5.2 put the ordinal two ahead of the id from record
142,842). The proof-of-reserves, transaction 830,874, is therefore record 830,876 here, row 514 of
the window counting from 0, in block 132,749; on the canvas its row is inked across 1,014
of the 1,024 columns, and the two rows above it across one. No row is blank. In 882 of
the 1,024 rows the newest block of the colour lies within ten columns of the right edge,
about 1,300 blocks or nine days, but not in all: in the other 142 it lies further left,
and in five of them before column 500 (these counts are read off the canvas by canvas_rows.py, a
script kept with figs_exact.py). These pictures were first drawn for a companion article on the
Mt.Gox cases, which draws their spend trees with tree-pdf, another binary of the crate;
they are kept here because they are pictures of the colour and not of any one case.
--sets --rows 830362..831386, every record before them coloured but not drawn. The
picture is folded onto cells of one record by about 130 block
ids, gamma . The blue wedge marks the Mt.Gox proof-of-reserves: transaction
830,874, record 830,876, in block 132,749 of June 2011. Its row is inked across 1,014 of
the 1,024 columns. Most rows are narrow, everyday payments with shallow provenance; the
full-width bands are transactions whose coins descend from essentially every era of the
chain. Main binary:
coloring-bt-transactions --sets --rows 830362..831386 --fold window_sets.png < finalBCUTXO_2022.scm.--weighted --gain 2000, on the cells of Figure 21: one
record by about 130 block ids, gamma . The declared gain lifts ink before the
gamma, so shades order cells but do not measure them. Even the full-width bands fade,
except where real value rides old blocks. Main binary:
coloring-bt-transactions --weighted --rows 830362..831386 --gain 2000 --fold window_weighted.png < finalBCUTXO_2022.scm.13.3 A ramp that reads#
The ramp of --palette is built in Oklab,Björn Ottosson. A perceptual color space for image processing. Blog post, December 2020. URL https://bottosson.github.io/posts/oklab/ not in HSL.
HSL’s lightness is not luminance and its hue circle is far from uniform (yellow at
and blue at have nominally the same lightness and are nothing of
the sort), so a ramp built in it has bands where the eye sees a step that is not there.
For a picture whose purpose is to compare magnitudes that is not cosmetic.
Lightness carries the magnitude, monotonically, which keeps the picture readable in grey,
readable to a colour-deficient eye, and readable where it is folded so small that a cell
is a sample rather than a shape. Hue and chroma only separate levels that lightness
leaves adjacent. Most of the chroma one would like at the dark end is outside sRGB.
Clamping the channels there shifts the hue and flattens the sweep, so the gamut mapping
holds lightness and hue fixed and bisects the chroma down until the colour fits: 256
colours, computed once (src/oklch.rs).
--palette ramp of src/oklch.rs, from paper on the left to the heaviest ink on the
right (the PLTE chunk stores it in the reverse order, ink first), drawn from the
write-up’s ramp.png, which matches ramp() entry for entry. Lightness falls
monotonically. The hue sweeps an arc of about rather than the full circle, so
the ends stay apart.13.4 One pixel per transaction#
The main binary’s examples/tint.rs (cargo run --release --example tint) reads a
--moments file, colors.moments.zst of §5.2, and draws each transaction as one
pixel: the mean block to hue over an arc of , and the concentration
to chroma. Over the whole chain that picture is nearly
one colour, and the reason is the data, not the drawing. The median spread is about
164,850 blocks, so 80% of the records have a concentration between 0.18 and 0.33 and only
3.4% exceed 0.5; and 80% of the hues fall in a stretch of about of the arc,
because the mean climbs with the record index. (These figures are quoted from the main
binary’s write-up. tint_stats.c, a program kept with the runs’ evidence outside the
crate, recounts them over all 778,613,440 lines of colors.moments.zst and agrees: a
median spread of 164,852 blocks, concentrations from 0.180 to 0.330 between the 10th and
90th percentiles, 3.39% above 0.5, and 38.8° between the 10th and 90th percentile
hues.) A fixed scale on a quantity this skewed spends the
channel on a few transactions, so the picture is not shown here. Its two questions, when
the coins were minted and how mixed they are, are asked elsewhere on axes that read: the
first by the colour surface of §12, on two time axes; the second by the spread of
§5.1, whose sketched error section 8 measures.
One lesson of the attempt stands, and it is about a scalar. Averaging the tints of the transactions that fall in a cell makes the cell nearly a function of its own position, for the same reason, so a binned picture of tints should sample one transaction per cell. Section 12 does average, but whole distributions rather than one number a transaction: the average of colours is again a distribution over the minting bands, a column is the expected colour of a transaction drawn at random from its band, and the structure that a tint would flatten (the diagonal, the halving steps) survives in it. What that average gives up is how the transactions of one band differ from one another.
tint --index also writes the tint as one byte a record: 778,614,320 bytes for the
chain, an 80-byte header, a 768-byte palette, the 778,613,440 bytes and 32 bytes for the
four places where the transaction id breaks its sequence (examples/tint.rs).
14. What Is Left#
- Bias at . Pass B ran one seed; the 3-seed test covers and only, and its 95% bounds (11.4% and 16.7% of the mean absolute error) are loose. More seeds would tighten both.
- in production. Its accuracy is measured; its emit size, time and memory
are projected. A 100M-record emit would firm them up (compare the first 100M records
at : 34.3 GB with
-12; a ratio above 2.3 would mean the 659–721 GB bracket is low). - Why
varopt’s error does not grow with depth. Corollary 12 proves the rate at every record, with a factor that is allowed to grow with depth; that the error relative to the colours’ spread stays flat, as measured, is not proved (§6.3). The control for the stratification explanation, VarOpt with its lights chosen in random order, was run only with the design-phase prototype on a prefix of the chain (§6.4); repeating it with the final binary over the whole chain is open. So is a direct look at the bound. On the first 3M records, where the exact colours are known, and could be computed record by record. is the squared norm of row of (§6.3), a solve with the identity on the right. Its rows hold an entry for every ancestor record rather than every ancestor block, so it is a heavier solve than the exact colours, and whether it fits on that prefix has not been measured. That would show whether the error stays flat because these sums stay small under mixing, or because the errors of different reductions cancel. - Literal bottom- against VarOpt. The literal weighted bottom- sketch of
sections 2–4 is
prio, and here it loses by 6–21×; the exponential (PPSWOR) ranks of §2.2 were tried in the design phase and were no different from priority ranks. Whether some bottom- variant can recover the rate (for instance by making the choice among the lights systematic, which is what VarOpt does) is open. - The band-based floors. The figure of TV1024 against its floor has to be redrawn with each row’s own before it can be shown; the numbers in §8.8 are the corrected ones.
--long=27sizes at , and are estimates: at from the 36.4% saving measured at , at from its own 40.7% measured over 0–350M, and at from an assumed saving of about 42%, extrapolated from the rise with . At the production run measured 172.7 GB, just below its estimate of 175–190 GB.- The permutation is pseudo-random. The exact unbiasedness of §10.4–10.5 is a theorem about a uniform permutation; the code draws a Fisher–Yates shuffle from a hash. The seed tests of §10.9 and the uniformity test T-K1 are the evidence that the difference is harmless, and a change to the shuffle or the hash must rerun them.
- One permutation per run. Every count and every cell of a matrix shares it, so errors are correlated across records and cells, and a single run can say nothing about bias. The production count file is one seed; R4 computed seeds 2 and 3 beside it but they are not shipped.
- Other weighted similarities. The Euclidean distance and the cosine of two colours
would need a store of Gaussian projections, and the Jensen–Shannon divergence one of
entropy sketches (§10.7); both would fold as the
l1store does, and neither was built. The KS distance between twovaroptsketches is written bypairsbut not checked against the exact colours. - Weighted similarity near the floor. The L1 store’s floor is 0.0088 at
, so pairs with smaller cannot be told apart one by one; a larger
lowers the floor only as . On the prefix that is most deep pairs across
time (92% below 0.01); over the whole chain it is a fifth of the
chainpairs and almost none inside a window. Thef32fold was checked againstf64on the first 3M records and, at full depth, only on the 1,280 records R5 selected ( relative at worst). L1 against the exact was checked on the prefix only: no record of the whole-chain selections has an unreducedvaroptsketch to compare with. At full depth there is only the band lower bound of §10.10, which holds but is loose inside a window. - A weighted sample that keeps the subset lemma. Ranks with a fixed function of the block keep Lemma 21, so they would fold exactly with exact weights, sampling blocks by a prior rather than by the colour. Which (recency, minted value) would serve or the functionals of §5.1 is open, and so is whether a weighted MinHash outside the class of Proposition 29 can compose under sums. The probability Jaccard index of Moulton and Jiang is not a function of L1, and no composing sketch for it is known here.
- Containment is often undefined for a small support against a large one (27% of
the ordered
evenpairs of the prefix one way, 14% the other; 0.78% of the cells of the whole-chain matrix), and its estimate is consistent but not unbiased: the inclusive threshold of the code biases it up by up to about (the full amount when is smaller than ). A strict threshold showed no bias in simulation; adopting it changes the output ofpairs, so it waits for a new version. The fallback is a biased ratio and is flagged. - More of the sketch for Jaccard. Both sketches are complete below the smaller threshold, so up to elements of the union are known; an estimator that uses them could lower the variance at small .
- KMV and L1 sketches of every record are not stored. At the KMV ones
would take about 3.2 TB. The counts are stored, and so is the
varopt:512colour of every record (§9); KMV and L1 sketches exist only for selections, and a new selection needs a new fold (about 70 minutes, as R5 took). - A value-weighted surface. The surface of §12 counts every transaction once. Weighted by the amounts, it would be the colour of the bitcoin that moved, and its comparison with the supply in §12.5 would be like with like. The amounts are not in the sketch file or the count file, so it needs one more pass over the chain with them, or over the share matrix of §7.12, which holds them (10.6 GB, not kept). The time since coins last moved, which coin-age charts use, is a different recurrence and is not in the colours at all.
sketchdoes not read the share matrix. Its runs parse the 150 GB of text (§7.12); reading the matrix through the main binary’s reader would save the parse of every pass.- The universe. Blocks must stay below , which at 144 blocks a
day the chain passes in about 2028;
:bits=21doubles the tables to 16 MiB.
15. Notes and References#
15.1 Further reading#
- Sampling theory. Horvitz and Thompson (1952) introduced the estimator that weights each sampled item by the inverse of its inclusion probability; every weight and linear-functional estimate of the priority and VarOpt sketches in this post, from priority sampling’s (§2.3, with rank threshold ) to the weight threshold carried by a kept light in VarOpt (§6.1), is one of them (the KMV counts, the Jaccard and containment ratios, and the Cauchy-scale L1 estimates of §1 and §10 are not). Madow (1949) belongs to the classical theory of systematic sampling, the design that §6.1 runs along the block axis. Chao (1982) is a fixed-size plan with unequal probabilities in which units enter the sample one at a time; the stream VarOpt of Cohen et al.Edith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Stream sampling for variance-optimal estimation of subset sums. In Proceedings of the Twentieth Annual ACM-SIAM Symposium on Discrete Algorithms, SODA '09, pages 1255–1264. Society for Industrial and Applied Mathematics, 2009a. doi: 10.1137/1.9781611973068.136. URL https://doi.org/10.1137/1.9781611973068.136 (one random eviction per arrival) draws exactly the same distribution of samples, while the systematic scheme of §6.1 keeps its inclusion probabilities but not its joint distribution.
- Resampling in particle filters. Kitagawa (1996) and Carpenter et al. (1999) introduced stratified and systematic resampling. Fearnhead and Clifford (2003) keep the particles above a threshold and resample the rest at the threshold’s weight. That is the reduction of §6.1, which they prove optimal among unbiased resampling schemes. Moral (2004) analyses particle systems through the decomposition of their error into the noises of the resampling steps, the analogue of §6.3. Gerber and Chopin (2015) beat the Monte Carlo rate by ordering the particles and using quasi-random points, and Gerber et al. (2019) prove that ordering speeds up stratified resampling. That is the gain of the block order in §6.4.
- Order sampling. Rosén (1997) studies the designs that give every unit an independent random ranking variable and keep the smallest: both rank families of §2.2 are of this kind. With the uniform ranks it is the sequential Poisson sampling of Ohlsson (1998), devised for the Swedish Consumer Price Index; with exponential ranks it is sampling without replacement with probability proportional to weight.
- Priority sampling and VarOpt. Duffield et al. (2007) is the source of §2–3: priority sampling, its unbiasedness and its zero covariances. Szegedy (2006) proved the near-optimality they had conjectured. Cohen et al. (2009a), in its journal version Cohen et al. (2011b), define VarOpt, whose estimates minimise the average variance over the subsets of every size; §6.1 keeps two of their three requirements and trades the third for the block order.
- Bottom- sketches. Cohen and Kaplan (2007) treat bottom- sketches as one family parametrised by the rank distribution, and Cohen and Kaplan (2008) derive their Horvitz–Thompson estimators by rank conditioning, the argument of §3. Thorup (2013) shows how little independence the hash function needs, for bottom- and for priority sampling alike. Cohen (1997) folds min-rank sketches through a graph to estimate the size of every node’s reachability set, the fold of §10.3.
- Counting distinct elements. Bar-Yossef et al. (2002) keep the smallest hash values; Beyer et al. (2007) name the KMV synopsis, prove the estimator of §1.2 unbiased, and extend it to multiset unions, intersections and differences. Flajolet et al. (2007) is the right-hand column of the table of §1.3, with a standard error of about for registers, and Broder (1997) the origin of MinHash and of resemblance as the Jaccard index of shingle sets.
- Structure and coordination. Cohen et al. (2011a)
design VarOpt samples that respect an order or a hierarchy on the keys, so that range
sums (here, the cuts of a colour’s CDF) are much more accurate; their appendix on
ordered keys sets systematic sampling beside them, which is the choice §6.1 makes.
Cohen et al. (2009b) coordinate samples of many weight
assignments over the same keys through shared ranks, as
coorddoes over the blocks in §6.6. - Weighted similarity of distributions. Manasse et al. (2010) define consistent weighted sampling, a MinHash for vectors whose collision probability is the weighted Jaccard similarity, and Ioffe (2010) makes it run in constant time per nonzero weight. Moulton and Jiang (2018) argue that for probability distributions, such as two colours, the natural generalisation of the Jaccard index is a different one, and give a MinHash for it, P-MinHash, whose ranks are those of Proposition 29. None of them composes through the sums of the colour recurrence; §10.6 uses instead that for distributions the weighted Jaccard similarity is a function of the L1 distance.
- Stable projections. Indyk (2006) sketches the L1 distance of streamed vectors by projections with Cauchy entries, which are linear and therefore follow any sequence of updates, including the mixtures of §5.1; Li et al. (2007) study estimators of the scale from Cauchy projections, among them the maximum likelihood estimator of §10.6, and their tail bounds. Jowhari et al. (2011) give samplers, linear sketches from which a coordinate can be drawn in proportion to its weight, the weighted sampling that does compose under sums (§10.6).
- Sparse triangular solves. Gilbert and Peierls (1988) solve a sparse triangular system in time proportional to the arithmetic, by first finding the nonzeros of the solution as the nodes reachable in the graph of the matrix, the fill-in that §5.3–5.4 measure; Davis (2006) (chapter 3) gives the algorithm and its code.
- Martingales. Williams (1991) covers what §6.2–6.3 use: conditional expectation, the tower property, and the orthogonality of martingale differences.
- Bitcoin and taint. Nakamoto (2008) describes the chain whose transactions are coloured here. Möser et al. (2014) define the poison and haircut blacklisting policies, the second of which is the recurrence of §5.1 read for one set of blocks; Anderson et al. (2018) propose first-in-first-out tracing instead, which in their case studies taints far fewer addresses than haircut.
- Randomness. Steele et al. (2014) is the SplitMix generator whose output function hashes every draw of §7.4. The permutation of §10.8 is the shuffle of Fisher and Yates in Durstenfeld’s in-place form, Algorithm P of Knuth’s §3.4.2.Donald E. Knuth. The Art of Computer Programming, Volume 2: Seminumerical Algorithms. Addison-Wesley, Reading, Massachusetts, 3rd edition, 1997. ISBN 0201896842. URL https://www-cs-faculty.stanford.edu/~knuth/taocp.html
15.2 References#
- Edith Cohen and Haim Kaplan. Summarizing data using bottom-k sketches. In Proceedings of the Twenty-Sixth Annual ACM Symposium on Principles of Distributed Computing, PODC '07, pages 225–234. Association for Computing Machinery, 2007. doi: 10.1145/1281100.1281133. URL https://doi.org/10.1145/1281100.1281133.
- Ziv Bar-Yossef, T. S. Jayram, Ravi Kumar, D. Sivakumar, and Luca Trevisan. Counting Distinct Elements in a Data Stream. In José D. P. Rolim and Salil Vadhan, editors, Randomization and Approximation Techniques in Computer Science: 6th International Workshop, RANDOM 2002, volume 2483 of Lecture Notes in Computer Science, pages 1–10. Springer, 2002. doi: 10.1007/3-540-45726-7_1. URL https://doi.org/10.1007/3-540-45726-7_1.
- Andrei Z. Broder. On the resemblance and containment of documents. In Proceedings. Compression and Complexity of SEQUENCES 1997, pages 21–29. IEEE Computer Society, 1997. doi: 10.1109/SEQUEN.1997.666900. URL https://doi.org/10.1109/SEQUEN.1997.666900.
- Kevin Beyer, Peter J. Haas, Berthold Reinwald, Yannis Sismanis, and Rainer Gemulla. On synopses for distinct-value estimation under multiset operations. In Proceedings of the 2007 ACM SIGMOD International Conference on Management of Data, SIGMOD '07, pages 199–210. Association for Computing Machinery, 2007. doi: 10.1145/1247480.1247504. URL https://doi.org/10.1145/1247480.1247504.
- Mikkel Thorup. Bottom-k and priority sampling, set similarity and subset sums with minimal independence. In Proceedings of the Forty-Fifth Annual ACM Symposium on Theory of Computing, STOC '13, pages 371–380. Association for Computing Machinery, 2013. doi: 10.1145/2488608.2488655. URL https://doi.org/10.1145/2488608.2488655.
- Philippe Flajolet, Éric Fusy, Olivier Gandouet, and Frédéric Meunier. HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm. In 2007 Conference on Analysis of Algorithms (AofA 07), volume AH of DMTCS Proceedings, pages 137–156, 2007. doi: 10.46298/dmtcs.3545. URL https://doi.org/10.46298/dmtcs.3545.
- D. G. Horvitz and D. J. Thompson. A Generalization of Sampling Without Replacement from a Finite Universe. Journal of the American Statistical Association, 47(260):663–685, 1952. doi: 10.1080/01621459.1952.10483446. URL https://doi.org/10.1080/01621459.1952.10483446.
- Edith Cohen and Haim Kaplan. Tighter estimation using bottom k sketches. Proceedings of the VLDB Endowment, 1(1):213–224, 2008. doi: 10.14778/1453856.1453884. URL https://doi.org/10.14778/1453856.1453884.
- Bengt Rosén. Asymptotic theory for order sampling. Journal of Statistical Planning and Inference, 62(2):135–158, 1997. doi: 10.1016/S0378-3758(96)00185-1. URL https://doi.org/10.1016/S0378-3758(96)00185-1.
- Nick Duffield, Carsten Lund, and Mikkel Thorup. Priority sampling for estimation of arbitrary subset sums. Journal of the ACM, 54(6), December 2007. doi: 10.1145/1314690.1314696. URL https://doi.org/10.1145/1314690.1314696. Article 32.
- Esbjörn Ohlsson. Sequential Poisson Sampling. Journal of Official Statistics, 14(2):149–162, 1998. URL https://www.scb.se/contentassets/ca21efb41fee47d293bbee5bf7be7fb3/sequential-poisson-sampling.pdf.
- Mario Szegedy. The DLT priority sampling is essentially optimal. In Proceedings of the Thirty-Eighth Annual ACM Symposium on Theory of Computing, STOC '06, pages 150–158. Association for Computing Machinery, 2006. doi: 10.1145/1132516.1132539. URL https://doi.org/10.1145/1132516.1132539.
- Satoshi Nakamoto. Bitcoin: A Peer-to-Peer Electronic Cash System, 2008. URL https://bitcoin.org/bitcoin.pdf.
- Malte Möser, Rainer Böhme, and Dominic Breuker. Towards Risk Scoring of Bitcoin Transactions. In Rainer Böhme, Michael Brenner, Tyler Moore, and Matthew Smith, editors, Financial Cryptography and Data Security: FC 2014 Workshops, BITCOIN and WAHC 2014, volume 8438 of Lecture Notes in Computer Science, pages 16–32. Springer, 2014. doi: 10.1007/978-3-662-44774-1_2. URL https://doi.org/10.1007/978-3-662-44774-1_2.
- Ross Anderson, Ilia Shumailov, Mansoor Ahmed, and Alessandro Rietmann. Bitcoin Redux. Workshop on the Economics of Information Security (WEIS 2018), Innsbruck, June 2018. URL https://www.cl.cam.ac.uk/~rja14/Papers/bitcoin-redux.pdf.
- Tin Tironsakkul, Manuel Maarek, Andrea Eross, and Mike Just. Probing the Mystery of Cryptocurrency Theft: An Investigation into Methods for Taint Analysis, 2019. URL https://arxiv.org/abs/1906.05754. arXiv:1906.05754.
- John R. Gilbert and Tim Peierls. Sparse partial pivoting in time proportional to arithmetic operations. SIAM Journal on Scientific and Statistical Computing, 9(5):862–874, 1988. doi: 10.1137/0909058. URL https://doi.org/10.1137/0909058.
- Timothy A. Davis. Direct Methods for Sparse Linear Systems. Fundamentals of Algorithms. Society for Industrial and Applied Mathematics, 2006. doi: 10.1137/1.9780898718881. URL https://doi.org/10.1137/1.9780898718881.
- Edith Cohen. Size-estimation framework with applications to transitive closure and reachability. Journal of Computer and System Sciences, 55(3):441–453, 1997. doi: 10.1006/jcss.1997.1534. URL https://doi.org/10.1006/jcss.1997.1534.
- William G. Madow. On the Theory of Systematic Sampling, II. The Annals of Mathematical Statistics, 20(3):333–354, 1949. doi: 10.1214/aoms/1177729988. URL https://doi.org/10.1214/aoms/1177729988.
- M. T. Chao. A general purpose unequal probability sampling plan. Biometrika, 69(3):653–656, 1982. doi: 10.1093/biomet/69.3.653. URL https://doi.org/10.1093/biomet/69.3.653.
- Edith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Efficient Stream Sampling for Variance-Optimal Estimation of Subset Sums. SIAM Journal on Computing, 40(5):1402–1431, 2011b. doi: 10.1137/10079817X. URL https://doi.org/10.1137/10079817X.
- Paul Fearnhead and Peter Clifford. On-line inference for hidden Markov models via particle filters. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 65(4):887–899, 2003. doi: 10.1111/1467-9868.00421. URL https://doi.org/10.1111/1467-9868.00421.
- Edith Cohen, Graham Cormode, and Nick Duffield. Structure-aware sampling: flexible and accurate summarization. Proceedings of the VLDB Endowment, 4(11):819–830, 2011a. doi: 10.14778/3402707.3402721. URL https://doi.org/10.14778/3402707.3402721.
- Lek-Heng Lim and Jonathan Weare. Fast Randomized Iteration: Diffusion Monte Carlo through the Lens of Numerical Linear Algebra. SIAM Review, 59(3):547–587, 2017. doi: 10.1137/15M1040827. URL https://doi.org/10.1137/15M1040827.
- Samuel M. Greene, Robert J. Webber, Jonathan Weare, and Timothy C. Berkelbach. Beyond Walkers in Stochastic Quantum Chemistry: Reducing Error Using Fast Randomized Iteration. Journal of Chemical Theory and Computation, 15(9):4834–4850, 2019. doi: 10.1021/acs.jctc.9b00422. URL https://doi.org/10.1021/acs.jctc.9b00422.
- Samuel M. Greene, Robert J. Webber, Timothy C. Berkelbach, and Jonathan Weare. Approximating Matrix Eigenvalues by Subspace Iteration with Repeated Random Sparsification. SIAM Journal on Scientific Computing, 44(5):A3067–A3097, 2022. doi: 10.1137/21M1422513. URL https://doi.org/10.1137/21M1422513.
- Jonathan Weare and Robert J. Webber. Randomly Sparsified Richardson Iteration: A Dimension-Independent Sparse Linear Solver, 2023. URL https://arxiv.org/abs/2309.17270. arXiv:2309.17270.
- Pierre Del Moral. Feynman-Kac Formulae: Genealogical and Interacting Particle Systems with Applications. Probability and Its Applications. Springer, 2004. doi: 10.1007/978-1-4684-9393-1. URL https://doi.org/10.1007/978-1-4684-9393-1.
- Mathieu Gerber and Nicolas Chopin. Sequential quasi Monte Carlo. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 77(3):509–579, 2015. doi: 10.1111/rssb.12104. URL https://doi.org/10.1111/rssb.12104.
- Mathieu Gerber, Nicolas Chopin, and Nick Whiteley. Negative association, ordering and convergence of resampling methods. The Annals of Statistics, 47(4):2236–2260, 2019. doi: 10.1214/18-AOS1746. URL https://doi.org/10.1214/18-AOS1746.
- Harald Niederreiter. Random Number Generation and Quasi-Monte Carlo Methods, volume 63 of CBMS-NSF Regional Conference Series in Applied Mathematics. Society for Industrial and Applied Mathematics, 1992. doi: 10.1137/1.9781611970081. URL https://doi.org/10.1137/1.9781611970081.
- Yichao Li, Wenshuo Wang, Ke Deng, and Jun S. Liu. Stratification and optimal resampling for sequential Monte Carlo. Biometrika, 109(1):181–194, 2022. doi: 10.1093/biomet/asab004. URL https://doi.org/10.1093/biomet/asab004.
- Beltran Borja Fiz Pontiveros, Mathis Steichen, and Radu State. Mint Centrality: A Centrality Measure for the Bitcoin Transaction Graph. In 2019 IEEE International Conference on Blockchain and Cryptocurrency (ICBC). IEEE, May 2019. doi: 10.1109/BLOC.2019.8751401. URL https://doi.org/10.1109/BLOC.2019.8751401.
- Edith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Stream sampling for variance-optimal estimation of subset sums. In Proceedings of the Twentieth Annual ACM-SIAM Symposium on Discrete Algorithms, SODA '09, pages 1255–1264. Society for Industrial and Applied Mathematics, 2009a. doi: 10.1137/1.9781611973068.136. URL https://doi.org/10.1137/1.9781611973068.136.
- Genshiro Kitagawa. Monte Carlo filter and smoother for non-Gaussian nonlinear state space models. Journal of Computational and Graphical Statistics, 5(1):1–25, 1996. doi: 10.1080/10618600.1996.10474692. URL https://doi.org/10.1080/10618600.1996.10474692.
- James Carpenter, Peter Clifford, and Paul Fearnhead. Improved particle filter for nonlinear problems. IEE Proceedings – Radar, Sonar and Navigation, 146(1):2–7, 1999. doi: 10.1049/ip-rsn:19990255. URL https://doi.org/10.1049/ip-rsn:19990255.
- David Williams. Probability with Martingales. Cambridge University Press, 1991. doi: 10.1017/CBO9780511813658. URL https://doi.org/10.1017/CBO9780511813658.
- Edith Cohen, Haim Kaplan, and Subhabrata Sen. Coordinated weighted sampling for estimating aggregates over multiple weight assignments. Proceedings of the VLDB Endowment, 2(1):646–657, 2009b. doi: 10.14778/1687627.1687701. URL https://doi.org/10.14778/1687627.1687701.
- Guy L. Steele, Doug Lea, and Christine H. Flood. Fast splittable pseudorandom number generators. In Proceedings of the 2014 ACM International Conference on Object Oriented Programming Systems Languages & Applications, pages 453–472. Association for Computing Machinery, 2014. doi: 10.1145/2660193.2660195. URL https://doi.org/10.1145/2660193.2660195.
- Piotr Indyk. Stable distributions, pseudorandom generators, embeddings, and data stream computation. Journal of the ACM, 53(3):307–323, 2006. doi: 10.1145/1147954.1147955. URL https://doi.org/10.1145/1147954.1147955.
- Ping Li, Trevor J. Hastie, and Kenneth W. Church. Nonlinear Estimators and Tail Bounds for Dimension Reduction in Using Cauchy Random Projections. Journal of Machine Learning Research, 8(83):2497–2532, 2007. URL https://www.jmlr.org/papers/v8/li07b.html.
- Mark Manasse, Frank McSherry, and Kunal Talwar. Consistent Weighted Sampling. Technical Report MSR-TR-2010-73, Microsoft Research, June 2010. URL https://www.microsoft.com/en-us/research/publication/consistent-weighted-sampling/.
- Sergey Ioffe. Improved Consistent Sampling, Weighted Minhash and L1 Sketching. In 2010 IEEE International Conference on Data Mining, pages 246–255. IEEE, 2010. doi: 10.1109/ICDM.2010.80. URL https://doi.org/10.1109/ICDM.2010.80.
- Ryan Moulton and Yunjiang Jiang. Maximally Consistent Sampling and the Jaccard Index of Probability Distributions. In 2018 IEEE International Conference on Data Mining (ICDM), pages 347–356. IEEE, 2018. doi: 10.1109/ICDM.2018.00050. URL https://doi.org/10.1109/ICDM.2018.00050.
- Hossein Jowhari, Mert Sağlam, and Gábor Tardos. Tight bounds for Lp samplers, finding duplicates in streams, and related problems. In Proceedings of the 30th ACM SIGMOD-SIGACT-SIGART Symposium on Principles of Database Systems, PODS '11, pages 49–58. Association for Computing Machinery, 2011. doi: 10.1145/1989284.1989289. URL https://doi.org/10.1145/1989284.1989289.
- Peter Clifford and Ioana Cosma. A simple sketching algorithm for entropy estimation over streaming data. In Proceedings of the Sixteenth International Conference on Artificial Intelligence and Statistics, Proceedings of Machine Learning Research, volume 31, pages 196–206. PMLR, 2013. URL https://proceedings.mlr.press/v31/clifford13a.html.
- Donald E. Knuth. The Art of Computer Programming, Volume 2: Seminumerical Algorithms. Addison-Wesley, Reading, Massachusetts, 3rd edition, 1997. ISBN 0201896842. URL https://www-cs-faculty.stanford.edu/~knuth/taocp.html.
- Björn Ottosson. A perceptual color space for image processing. Blog post, December 2020. URL https://bottosson.github.io/posts/oklab/.