{'fraction_non_alphanumeric': 0.03482173079092858, 'fraction_numerical': 0.006092745120162473, 'mean_word_length': 4.30884995507637, 'pattern_counts': {'":': 0, '<': 26, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Adaptive Threshold Sampling

Sampling is a fundamental problem in computer science and statistics. However, for a given task and stream, it is often not possible to choose good sampling probabilities in advance. We derive a general framework for adaptively changing the sampling probabilities via a collection of thresholds.In general, adaptive sampling procedures introduce dependence amongst the sampled points, making it difficult to compute expectations and ensure estimators are unbiased or consistent. Our framework address this issue and further shows when adaptive thresholds can be treated as if they were fixed thresholds which samples items independently. This makes our adaptive sampling schemes simple to apply as there is no need to create custom estimators for the sampling method. Using our framework, we derive new samplers that can address a broad range of new and existing problems including sampling with memory rather than sample size budgets, stratified samples, multiple objectives, distinct counting, and sliding windows. In particular, we design a sampling procedure for the top-K problem where, unlike in the heavy-hitter problem, the sketch size and sampling probabilities are adaptively chosen.


Introduction
Sampling is a fundamental problem in computer science and statistics. By reducing the amount of data processed, it can significantly improve performance and lower costs, or it can ensure that the data processed fits within a system's resource constraints. Of particular interest are random sampling without replacement procedures as they do not sample redundant information.
Before observing the data, it is not possible to choose appropriate sampling probabilities. For example, given a weighted stream of unknown length, it is impossible to choose a sampling probability ahead of time that ensures the sample satisfies a finite memory budget B. To guarantee a finite budget is satisfied, each item's inclusion decreases the available budget and affects the inclusion probability of other items. This dependence causes several difficulties when designing sampling procedures and deriving estimators. In particular, the dependence often makes it intractable to compute the inclusion probability for each item or sets of items. When these sampling probabilities cannot be estimated, the sample is almost useless in data analysis. Good estimates cannot be obtained since estimators must adjust the contribution of each item based on its inclusion probability.
These difficulties can extend to designing sampling procedures. When the sample size is not fixed, items can be drawn independently with weight w i with probability π i ∝ w i . For example, the Conditional Poisson Sampling scheme is one that draws a fixed size sample and has desirable properties; however, no known algorithm can efficiently draw Conditional Poisson samples.
We propose a framework, adaptive threshold sampling, that addresses all of these challenges. We use it to solve novel problems and improve existing solutions. In this framework, samples are easy to draw; sample sizes and probabilities can change on the fly; and good estimators can be derived even though samples are dependent. This framework mimics drawing independent (Poisson) samples. Each item x is associated with an independent random value R x and a threshold T x . The item is included in the sample if R x < T x . Rather than choosing a constant threshold T x , we adjust the threshold in a data and sample dependent way to obtain desirable properties.
Our methodological contributions revolve around making it simple to build thresholds where the resulting sample is easy to analyze. We establish conditions when the threshold T x can be treated as if it was a fixed threshold that yields an independent sample. This simplifies analysis of the sample since one can apply an existing unbiased estimator for independent samples. Deriving and analyzing a custom estimator based on the true sampling distribution becomes unnecessary. When the conditions do not hold, we introduce a more general notion of threshold recalibration that makes it easy to compute expectations and derive new unbiased estimators for a broader class of thresholding rules. We also provide methods for building and composing thresholds and for merging samples. We also prove an empirical process convergence result that further simplifies the development of good estimators and sampling designs. It extends our theory for unbiased estimators and shows when consistent estimators for independent samples remain consistent when applied to adaptive thresholding samples. It also provides justification for heuristic thresholding schemes that do not satisfy our conditions for unbiased estimation but satisfy an asymptotic convergence condition which may be easier to verify.
Our contributions to applications exploits our methodological contributions to develop new or improved sketches and estimators on a range of new and existing problems. For example, we double the effectiveness of the state-ofthe-art in sampling from sliding windows [14] even though we use exactly the same sketch to construct the sample. We improve merge procedures for distinct counting sketches, handle budget constraints for samples given variable length items, and provide a solution to a novel top-k problem, a more challenging variation of the well-studied heavy hitter problem, where the top-k items by frequency must be returned regardless of how small their frequency may be.

Related work
A long line of work has studied the bottom-k sample [24,25,12,8], showing how it can be used to draw weighted samples while deriving good estimators for sums over subpopulations as well as estimates of their variance. These bottomk sampling methods can be considered an adaptive threshold sampling method where the threshold ensures the sample size is exactly k. Extensions [9,6] study combining bottom-k samples. Another techniques for efficiently drawing fixed size k samples is VarOpt sampling [7].
Little work has provided generalizations of the bottom-k thresholding rule while providing a unbiased estimators. One notable exception is in distinct counting applications using Uniform(0, 1) priorities. The Theta sketch [11] provides a general 1-goodness condition. Thresholding rules that satisfy this ensure cardinality estimates are unbiased. For uniform sampling, a generalized thresholding rule has been used for distributed sampling [33].
In addition to providing an adaptive sampling framework, our contributions also use it to address novel problems and improve existing methods. Novel problems include sampling with fixed memory budgets, multi-stratified sampling, and top-k queries. These problems are more difficult variations of existing problems. Examples of existing sketches and sampling methods that are improved include sampling in sliding windows [14] and distinct counting [15,29,11]. Our applications are provided as examples of our framework's usefulness. Bottom-k methods have been used in numerous other applications such as set similarity [5], networking [26], time-decayed sampling [10], and distributed sampling [19,13,33] 2 Sampling design and estimation We first review sampling without replacement and the use of fixed thresholds for drawing samples. One key contribution of our paper is under what conditions can a random, adaptive threshold be treated as if it was a fixed threshold.
The notion of weighted or unequal probability sampling is at the core of many sampling problems. Sampling more informative items with higher probability leads to lower variance estimates. Choosing an appropriate measure of informativeness allows for accurate estimation for problems ranging from simple aggregates to complex machine learning models [32]. Unequal probability sampling can also arise in other situations, such as in stratified sampling where strata can have different sampling probabilities or in distributed sampling where nodes may make independent choices about the sampling rate.

Poisson sampling with thresholds
The simple sampling scheme where the inclusion decisions for each item is independent of all others is of particular interest. That is where Z i = 1 if item x i is included in the sample. Such schemes are called Poisson Sampling designs. This is not to be confused with Poisson distributed random variables. In this case, the desired inclusion probability π i for each x i must be known in advance. A fixed threshold can be used to draw such a sample. Associate an independent auxiliary variable R i for each item along with a fixed threshold T i . The item Choosing a threshold such that π i = F i (T i ) yields a sample from the desired sampling design. We call the variable R i the priority of x i and denote the inclusion of x i by Z i = 1(R i < T i ). From this, it is easy to see how the threshold T i can be used to adjust the inclusion probabilities.

Sampling challenges and estimation
However, unequal probability sampling can lead to challenges in sampling and estimation. For example, under memory budget or sample size constraints, Poisson sampling can violate the constraints since there is some non-zero probability that all items are sampled. It is thus natural to consider samplers that draw fixed size samples. The natural extension of Poisson sampling to fixed sizes is Conditional Poisson Sampling (CPS), which is obtained from a Poisson Sampling design conditional on the sample size being exactly k. The Conditional Poisson Sampling design has the attractive property of being the maximum entropy sampling procedure for a set of inclusion probabilities. However, there is no efficient algorithm known for drawing a CPS sample or for computing the inclusion probabilities [28].
Estimating quantities of interest can be even more problematic. A sample is almost useless without good estimators. In unequal probability sampling designs, an unbiased estimate of the population total S is given by the Horvitz-Thompson (HT) estimator,Ŝ where Z i indicates if the item x i is included in the sample and π i = p(Z i = 1) is the inclusion probability. This also provides a solution to the subset sum problem [12] by zeroing any value x i that is not in the desired subset. The fundamental problem for Conditional Poisson sampling and other sampling schemes with dependence between items' inclusion is that this dependence makes inclusion probabilities and good estimators difficult to derive. If the problem of efficiently sampling and computing inclusion probabilities can be overcome, then it is possible to search for an optimal sampling design given this estimator. When the inclusion probabilities π i ∝ x i , each term in the HT estimator is constant. Furthermore, if the sample size is fixed at k, the HT estimator itself is constant, and thus has minimal variance. A sample that draws elements with probability proportional to some size x i is called a probability proportion to size (PPS) sample.

Adaptive threshold sampling
Designing good sampling procedures is further complicated by the fact that the desired inclusion probabilities are often not known in advance. They may depend on unknown properties of data stream such as length or the variance of the data.
Our solution to the challenge of adaptively choosing the desired probabilities is to replace the fixed threshold generating an independent Poisson sampling scheme with an adaptive threshold that can depend on the data. For example, adaptively choosing the threshold can ensure that the sample fits inside a memory budget regardless of the size of the stream.
Mathematically, we define an adaptive threshold T i = τ i (R|D) to be a function τ i of the data D and priorities R that determine the sample. Like Conditional Poisson Sampling, this dependence between the threshold and the priorities makes it difficult to compute the inclusion probability p(Z i = 1) = p(R i < T i ) needed by the HT estimator and can make unbiased estimators difficult to generate. For example, suppose the data consists of individuals' demographic information. In an extreme case, consider the threshold T i := min{R j : gender j = Female}. Such a sample is grossly biased as it would exclude all females. Generating an unbiased estimator of the population is impossible for this sampling scheme.
Given the challenges introduced when samples are not drawn independently, we are interested in the following questions. If the thresholds depend on the data, when can an unbiased or consistent estimator still be derived from the sample? Furthermore, when can the adaptive thresholds be treated as if they are fixed thresholds? An unbiased estimator for the fixed threshold would then automatically give an unbiased estimator for the adaptive threshold.

Function classes
Though the dependence between items makes computing arbitrary expectations difficult, we show expectations are easy to compute for restricted classes of functions. We consider two function classes.
Our first goal is to examine when one can apply an unbiased estimator for a fixed threshold sampler to get an unbiased estimate for an adaptive threshold sampler. Given an adaptive thresholding scheme , we seek to find the most general form of an estimator that allows the such a substitution. We first note that when sampling, any estimator is naturally restricted to be a function on the sample. This general class of functions can be expressed as the polynomial For the first class of functions, we consider a simpler class of polynomials of the form Here, Λ 0 ⊂ P([n]) where P([n]) is the powerset of the indices [n] := {1, . . . , n}.
A subscript of λ selects the indices in λ. Since the priorites R determine Z and T we also write the estimator asθ(R, T ) orθ(R). This form as a polynomial is particularly useful as the linearity of expectations allows each monomial term's expectation to be computed separately. By further restricting the class of functions, we can capture a wider range of adaptive thresholding schemes where one has existing unbiased estimators. The second function class, the important set of pseudo-HT estimators, are of the formθ Rather than each item having a single threshold, an item's threshold can change depending on the term λ in the sum. Since the thresholds can be different, the inclusion indicationsZ λ can be as well.
We note that the restriction to pseudo-HT estimators is mild. For any i.i.d. sample from a distribution G, any estimable parameter of the distribution G is equal to Eh(X 1 , . . . , X m ) for some finite m and symmetric function h [16]. This form, which is that of a U-statistic, is an even more restricted form than that of an HT-estimator.

Threshold recalibration
When using an adaptive threshold sampling rule, the main difficulty in computing expectations is due to the interdependence of the threshold and priorities. Our main idea is that, if we consider a monomial term Π i∈λ Z i , the true adaptive threshold T can be replaced with an alternative threshold T λ that is independent of the priorities R λ . Here, superscript λ is used to denote quantities whose values depend on λ, while subscripts select indices.
This can also be seen as creating an alternative threshold sampling procedure for every monomial term. Since each monomial corresponds to a subset λ of all the items, the alternative threshold can adapt to the data using only items not indexed by λ. As long as the alternative thresholds are not larger than the original ones,T λ λ ≤ T λ , the sample using the alternative can be computed from the sample using the original threshold. We are particularly interested when the alternative and original thresholds are equal,T λ λ = T λ . These alternative thresholding rules are created in the following manner. Let n be the possibly unknown number of items and R −λ denote the vector of priorities excluding those indexed by λ. Define the recalibrated thresholding rule and threshold with respect to λ bỹ In other words, given a set of priorities, we find the smallest possible threshold with the given values of R −λ while ignoring the values of priorities R λ . When the thresholding rule τ is non-decreasing, the alternative threshold is obtained by setting every priority R i for all i ∈ λ to the smallest possible value. These recalibrated thresholds yield a modified set of inclusion indicatorsZ λ i = 1(R i < T λ i ).
Although the true inclusion probability remains intractable to compute, computing a conditional inclusion probability is easy. Lemma 1. The conditional inclusion probability given the recalibrated threshold is This provides the ability to estimate any statistic as long as the sample size is large enough.
Theorem 2. Given a statistic θ = λ∈Λ0 h λ (x λ ), the pseudo-HT estimator below using recalibrated inclusion indicatorsZ and thresholdsT is an unbiased estimator for θ.θ Proof. Conditioning onT λ and applying the tower rule gives The lemma trivially gives an unbiased estimator for subset sums.
Corollary 3. For any subset C ⊂ [n], the following conditional HT-estimator based on the alternative thresholds is an unbiased estimator for the subset sum .

Example: Bottom-k sketches and priority sampling
Priority sampling and other bottom-k sampling procedures choose the threshold to be the (k + 1) th smallest priority R (k+1) . Since the thresholding rule is nondecreasing, we can recalibrate the threshold for any item x i in the sample by changing the priority R i to −∞. These priorities were already smaller than the (k+1) th smallest priority, so changing them to −∞ does not affect the threshold, andT i i = T i . Thus, the HT-estimator is unchanged when the original threshold T is substituted with the recalibrated thresholdT , and is an unbiased estimator of the sum if F i (T i ) > 0 for all i ∈ C. The main differences when deriving an unbiased estimator using threshold recalibration compared to using existing methods are that (1) threshold recalibration provides a constructive procedure for updating the thresholds while existing derivations must first propose a new thresholding rule that is then verified to match the existing one, and (2) we allow the alternative thresholds to differ for every monomial term. However, we are most interested in the case where the original thresholds and the recalibrated ones are the same. In this case, the original adaptive thresholds can be treated as fixed thresholds for the relevant class of functions.

Threshold substitutability
Suppose the recalibrated thresholdsT λ are equal to the original ones whenever the subset λ is in the sample. Formally, for any subset λ, Z λ i = 1 ∀i ∈ λ =⇒T λ λ = T λ . We call thresholds that satisfy this substitutable thresholds. If a threshold only satisfies this when |λ| ≤ d then we call it a d-substitutable threshold. Substitutable thresholds have several attractive properties. Most importantly, unbiased estimators derived under a fixed thresholding scheme are also unbiased under the true adaptive sampling scheme under modest regularity conditions. Thus, substitutable thresholds can be treated almost like fixed thresholds.
Theorem 4 (Threshold substitution). Let T be a substitutable threshold. Suppose the estimatorθ in the form given in 2. Then θ(R, T ) =θ(R,T ).
This also holds if τ is d-substitutable andθ is at most a d degree polynomial in Z.
Proof. Consider a term β λ (x λ , T λ ) i∈λ Z i . If i∈λ Z i = 1 then the recalibrated thresholdT λ λ = T λ does not change. Thus,Z λ λ = Z λ as well, and  The definition of a substitutable thresholding rule requires verifying that the original thresholds equal recalibrated thresholds with respect to every possible subset of indices. We now provide a simpler condition to verify substitutability that recalibrates with respect to singletons.
Theorem 6 (Substitutability from singletons). Let τ be a non-decreasing adaptive thresholding rule generating the threshold T . If for any i ∈ {1, . . . , n}, Proof. Let τ (R) = T be the thresholding function for T . We must verifỹ T λ λ = T λ for all subsets λ with non-zero probability of being selected. Without loss of generality assume the subset to be verified is λ = {1, . . . , k}. If j∈λ Z j = 1, then R j < T j for all j ∈ λ. The singleton substitutability assumption allows us to incrementally substitute one coordinate R j with any value r j < T j without changing the threshold if j ∈ λ. Using induction, we have T = τ (r 1 , r 2 , . . . , r k , R k+1 , . . . , R n ) whenever r j < T j for all j ∈ λ. Since the recalibrated thresholdT λ is simply the infimum over the coordinates indexed by λ, it follows thatT λ λ = T λ .

Variance of the HT estimator
The value of threshold substitution is that it makes it trivial to obtain unbiased estimators under adaptive threshold sampling. One can simply reuse an existing estimator for a simple, Poisson sampling design. We illustrate the ease in estimating the variance of an HT estimator using our framework. In comparison, the priority sampling paper [12] required a one and a half page derivation. Section 2.5.1 showed that the bottom-k and priority sampling threshold satisfies the conditions of Corollary 6. Thus, it is substitutable. The well-known variance of the HT estimatorθ t under fixed threshold sampling with threshold t and an unbiased estimator of this variance are given by The squared error (θ(Z, T )−θ) 2 is in the function class given by equation 2 since the coefficient for any monomial Z λ depends only on T λ , x λ . Hence, the variance estimator for the HT estimator on fixed thresholds is also unbiased for the adaptive bottom-k threshold. That is, V ar(θ T ) = V ar(θT ) = EV ar(θT |T ) = E V ar(θT |T ) if k ≥ 2 due to the tower rule and unbiasedness ofθ.

Other statistics
A slightly more complex case than a subset sum is Kendall's τ correlation. Given random X, Y ∈ R n , Kendall's τ statistic is This is an alternative to the usual correlation Cov(X, Y )/ V ar(X)V ar(Y ). It can capture some non-linear dependencies and is robust to outliers. It can be used to perform a hypothesis test whether two variables are dependent. If a threshold T is 2-substitutable, then an unbiased estimate of Kendall's τ is . This is a form of HT-estimator, but the terms Z i Z j in the estimator are correlated. This requires the more general form of the HT-estimator's variance: are the pairwise and four-wise inclusion probabilities. Like above, we can apply Horvitz-Thompson under Poisson sampling to estimate this sum using only sampled items by replacing . Given a substitutable threshold T , Theorem 4 shows that we can use π ij = F i (T i )F j (T j ) and π ijk = i ∈{i,j,k, } F i (T i ) Since ( T − T ) 2 is a 4 th degree polynomial in the function class given in equation 2, it is an unbiased estimator of the variance as long as the sample always contains at least 4 items.
Other statistics of interest include skew and kurtosis. The skew is µ 3 /σ 3/2 while the kurtosis is µ 4 /σ 4 . Here, µ k = E(X − E X) k is the k th central moment and σ 2 is the variance. Like variance estimates, the sample central moments are biased estimators of a distribution's population moments. Our theory reuses existing unbiased estimators for the population moments µ k . For example, [17] provides an unbiased estimator for the k th central moment as a degree k Ustatistic. Section 2.4 showed that U-statistics have an unbiased HT-estimator. Hence, plugging in adaptive thresholds into this estimator yields an unbiased estimate of the population moments whenever the threshold is k-substitutable.
Each of these cases follow a simple paradigm. Adapt an existing estimate to use samples under a simple Poisson sampling design. Check a condition for the adaptive thresholds. If it holds, the estimator is unbiased when plugging in the adaptive thresholds.

Sequential thresholding rules
The last class of thresholds and functions consists of thresholds whose values can be determined in a sequential manner. Although these thresholds may not be substitutable, we show they can yield unbiased HT-estimators. The following example motivates this.
Example (1-substitutable threshold): Suppose a data stream is processed using a bottom-k sketch. Instead of storing only items in the final state of the bottom-k sketch, suppose an item is stored as long as it was in the bottom-k sketch at some point in the stream. This allows aggregates to be computed over time windows [0, t] for any time t. In this case, the threshold rule τ i is a function of the priorities R 1 , . . . , R i−1 . τ is trivially 1-substitutable since it does not depend on R i . However, the threshold is not 2-substitutable. To see this, consider the state of the sketch after processing the entire stream, and let x j be the last item included in the sample. If the data stream is sufficiently large, then the threshold T j must be equal to a priority R i of an item that appeared earlier in the stream and was included in the sample but was kicked out of the sketch before the end of the stream. If that earlier priority R i changes, then the later threshold T j also changes. Thus, while 1-substitutability allows us to use the HT estimator for sums, it does not allow us to compute unbiased estimates of variances.
However, despite being non-substitutable, we show this threshold can still be treated like a fixed threshold for pseudo-HT estimators. We show that if there is an ordering of the data such that the thresholding choices are made sequentially, then a pseudo-HT estimator is unbiased. That is, we must show Theorem 7. Given a permutation ρ 1 , . . . , ρ n of [n], define the future samples at time j to be S j (ρ) = {ρ k : Z ρ k = 1, k≥j}. If there exists a permutation ρ such that the recalibrated thresholdsT for any λ such that p( i∈λ Z i = 1) > 0.
Proof. This is a straightforward application of Fubini's theorem.
where k denotes the largest index such that ρ k ∈ λ. The terms Z i /F i (T i ) for i ∈ λ\{ρ k } are unaffected by integration over R ρ k since ρ k is the index for a future sample for i, and the recalibration condition ensures that modifying priority R ρ k does not affect the threshold T i as long as R ρ k < T ρ k .
In one special case where the permutation puts the priorities in sorted order, a stronger full substitutability result is obtained.
If M is a stopping time with respect to the filtration defined by this sequence, then the rule Proof. The items λ = {ρ M +1 , . . . , ρ n } are in the sample. By the definition of a stopping time, the threshold R ρ M is a function of R ρ1 , . . . , R ρ M . Furthermore, it is non-increasing. Applying threshold recalibration and replacing R j with −∞ for all j > M does not change the ordering of the first M priorities. Thus, the threshold does not change, and the threshold is substitutable.

Building and composing thresholds
Thus far, we have described methods for taking an existing thresholding rule and modifying it to allow for unbiased estimation. We now examine how thresholds can be composed and samples can be merged. A simplified interpretation of our result states that the maximum of 1-substitutable thresholding rules yields another 1-substitutable rule, and the minimum of fully or d-substitutable rules yields another fully or d-substitutable rule respectively. Composing d-substitutable or fully substitutable thresholding rules preserves d-substitutability or full substitutability. Theorem 9. Let T 1 , T 2 be 1-substitutable thresholds on a data set D with priorities R. Let the items sampled according to T j be denoted by D j and their indices by I j . Consider a thresholding rule τ where τ i is a function of Proof. For 1-substitutability, note that changing the priority R i for any i ∈ I 1 ∪I 2 does not change T 1 i , T 2 i . Hence, it also cannot change T i . Similarly, when T 1 , T 2 are substitutable, one can recalibrate priorities for items in D j without affecting T j . Hence, recalibrating priorities for items in D 1 ∩D 2 affect neither T 1 nor T 2 . These are precisely the set of items with priority R i ≤ min{T 1 i , T 2 i }.

Priority-threshold duality
Another useful property of adaptive threshold sampling is that adjusting priorities is equivalent to adjusting thresholds. An item with a priority distribution is less than the pseudo-inclusion probability. This can be used, for example, when the importance of an item and its priority distribution can change over time.
For instance, in time-decayed sampling [10] with exponential decay, the weight of an item w i (t) = w i exp(−t) decreases exponentially with time t after the item appear at time t 0 i . Thus, one can build a sampling method which uses adaptively chooses a threshold T (t) given time varying weights w i (t). An item is included in the sample at time t if its priority R i (t) = U i /w i (t) < T (t) However, it is inconvenient in practice to change the weight of existing points. Changing the threshold to increase exponentially instead, allows the priorities to remain fixed. An item is included if

Applications and Sampling designs
Although the definitions and theorems in section 2.3 are subtle and abstract, we now show that they are powerful, allowing us to easily generate sampling schemes that solve novel problems † , improve existing sketches * , and unify the theory for multiple sampling methods ‡ . We label the sections with the respective symbol † , * , or ‡ to note the contribution our paper makes.

Variable item sizes †
Bottom-k sketches ensure the sample size is always k. However, the memory usage of the sample can vary if items have different sizes. To guarantee a sample fits within a given memory budget B, the parameter k must be set conservatively to B/L max where L max is the size of the largest item. This is highly inefficient if the largest item is much bigger than the average item. Another thresholding rule τ simply takes as many items as possible that fit within the memory budget. If priorities are sorted in ascending order, the threshold is the priority of the first item which causes the budget to be exceeded. Like a bottom-k sketch, the values of the smaller priorities are irrelevant and can be set to 0, so the threshold is substitutable. Thus, if the budget B ≥ L max so every item has a non-zero chance of being selected, the usual HT estimator provides estimates of subset sums, and if B ≥ 2 L max the usual HT variance estimator provides unbiased estimates of its variance.
For example, items in the 2020 Kaggle data science survey can vary in size since the survey contains both long, text free responses and cases where the respondent does not finish the survey. As a string, the maximum length of an item is 5113 characters while the average length is 1265. A bottom-k sample that is guaranteed to fit within a budget constraint is expected to be 1/4 th the size of an adaptive threshold sample that utilizes the entire budget.

Sliding windows *
Oftentimes, only recent items in a data stream are of interest. A sliding window sampler draws a uniform sample from points that arrive in the time interval (t− ∆, t] where t is the current time and ∆ is the length of the time window. When the arrival rate of items changes over time, it can be impossible to draw a fixed size sample in bounded space [14,4]. The state-of-the-art for drawing uniform samples from sliding windows in bounded space is given by Gemulla and Lehner (G&L) [14]. We show this is an instance of adaptive threshold sampling, but a highly inefficient one. Our framework immediately yields improved thresholds that double the number of usable points with zero modifications to the sketch.
At time t, the G&L scheme consists of one set of expired samples X(t) that occur in the time window (t − 2∆, t − ∆] and another set of current examples C(t) in the window (t − ∆, t]. Although G&L do not describe their procedure as a thresholding scheme, we describe it as a two stage thresholding scheme, one which samples non-uniformly to build candidate points and one which provides the final uniform sample. The initial threshold T n (t n ) for an item x n at time t n is 1 if there are fewer than k current examples. Otherwise, T n (t n ) is the k th smallest priority of the current sample C − (t n ) just before time t n and the new priority R n . We note that this can be larger than the k th smallest priority for all items in the current time window. Some items not in the current sample may have a smaller threshold and have already been discarded. If there are ever more than k current examples, the largest priority item is discarded by adjusting the threshold of all the current examples, T i (t n ) = min{T − i (t n ), T n (t n )}. An example that falls out of the current window is moved from the current to expired examples, and any expired item that is two window lengths or more from the current time is discarded. This threshold determines whether or not an item is stored but does not ensure that it is a uniform draw from a sliding window.
The G&L scheme assigns a final threshold T GL equal to the k th smallest priority of the combined current and expired examples. This is guaranteed to return a uniform sample from the current time window, although the sample size is not fixed. In this case, the item corresponding to the threshold can be included in the sample due to symmetry.
This bottom-k threshold, however, results in an inefficient threshold that discards half of the useful points. To see this, suppose that items arrive at a uniform rate of 1000 per second and are assigned Uniform(0 , 1 ) priorities. Given a 100 second time window and a maximum memory budget of 1000 samples in the current window, the initial threshold for each item must be roughly T i ≈ 1% to satisfy the budget. However, G&L takes the bottom-1000 threshold of items in both the current and expired windows, which contains 200,000 items. This gives a threshold of roughly 0.5%. Since all thresholds are T i ≈ 1% and we simply take the min of thresholds in the current window, we will return a threshold near the ideal threshold of 1%.
Our adaptive thresholding framework immediately provides a much improved threshold. We note that the thresholding rule consists of two parts, a  Figure 1 shows the evolution of the per item thresholds T i (t i ) over time and the much smaller threshold used by G&L to construct a sliding window sample. Figure 2 shows the behavior when there is a spike in the item arrival rate. Not only does our adaptive threshold sampling framework yield nearly twice as many samples when the item arrival rate is steady, it recovers from the spike faster.

Adaptive sampling for top-k and disaggregated subset sums †
Adaptive thresholding can also be used to modify a frequent item sketch into a top-k sketch that also supports further aggregations. Given a parameter m, a frequent item sketch returns all items where the proportion of times each appears is > 1/m. This can be done with O(m) space using the Misra-Gries [23] or equivalent Space-saving sketch [22]. The top-k problem requires returning the top k items by frequency. Unlike the frequent item problem, there is no guarantee on the minimum proportion of times these top-k items appear. This makes the top-k problem a more challenging variation of the frequent item problem. To use frequent item sketches for the top-k problem, the appropriate size parameter m must be known in advance. It can also be useful for the sketch to support further aggregations. For example, one may wish to analyze web page impressions and find the frequently viewed pages. One may then wish to further aggregrate pages by topic. This disaggregated subset sum problem is addressed by [30,21]. This problem can be seen as an adaptive sampling procedure which learns to downsample infrequent items, leaving the frequent ones. By virtue of being an adaptive threshold sampling procedure, it automatically supports unbiased estimation of counts and further aggregations using the HT-estimator. This leads to the following adaptive threshold sampling procedure. For each point x t in a data stream, assign a U nif orm(0, 1) priority R t . Maintain a variable length list where each entry consists of an item x i , its priority R i , a threshold T i , and a count v i of the times it appeared after entering into the sample. An unbiased estimate of the count of an item isĉ i = 1/T i + v i . This is the Horvitz-Thompson estimate where one appearance of the item has pseudo-inclusion probability T i while the other v i appearances have probability 1. We define the adaptive threshold T (t) at time t to be the smallest priority such that at least k items in the sample have estimated countĉ i > 1/T (t). This splits the items in the sample into infrequent items withĉ i ≤ 1/T (t) and k frequent items witĥ c i > 1/T (t). Whenever the adaptive threshold T (t) is updated, only infrequent items are updated. Those with priority R i ≥ T (t) are discarded. All others update their threshold to T (t) and their counter to v i = 0.
This procedure can be seen as a thresholding based variation of Unbiased Space-Saving [30]. In both, infrequent items form a random sample of the items not assigned to a frequent item counter. Items start as infrequent items and maintain a count of the number of times each occurred after entering the sample. It is easy to see that this thresholding rule is substitutable. For any subset of items in the sample, changing their priorities to 0 has no effect on the sample or thresholds. Thus, like Unbiased Space-Saving, it can be used for unbiased estimation for the disaggregated subset sum problem.
We compare our adaptive procedure with the FrequentItems sketch in Apache Datasketches [2,1]. This FrequentItems sketch is a variation of the Misra-Gries sketch [23,22] that allows for faster updates. For each sketch, we query for the top-k items in a stream with k = 10 and record the number of errors in the result. Since we wish to compare performance as the distribution of the heavy hitters changes, we use a synthetic Pitman-Yor(1, β) preferential attachment process that is able to generate both light tailed and heavy tailed behavior. It is commonly used in Bayesian cluster models. Larger values of β ∈ [0, 1) result in heavier tails. More precisely, in the Pitman-Yor process, the t th item in the stream is a new item with probability (1 + βC t )/t where C t is the number of unique items seen already. Otherwise, it is equal to the j th unique item with probability (n tj − β)/t where n tj is the number of times unique item j has been seen amongst the first t − 1 items. Figure 3 shows that our procedure can accurately capture the top-k items without prior knowledge of the distribution. It does so by appropriately adjusting the size of the sample so that it captures the top-k items with high probability. For distributions where the the frequent items are well-separated from the remaining items, our adaptive sampler requires even less space than the FrequentItems sketch. For distributions where frequent items are not well separated from infrequent items, the FrequentItems sketch performs poorly. In contrast, our adaptive procedure captures the frequent items by adjusting its size to the data. For FrequentItems, we take the size to be 0.75 times the size of the allocated hash table.

Distinct counting for weighted samples ‡
The subset sum and distinct count problems are often treated as separate problems. However, they can be addressed using a single weighted, coordinated priority sample. For example, in a freemium model, one may wish to sample paying users with probability proportional to spend but may still wish to estimate the total population size of both paying and non-paying users in a For any subset A, estimate the subset sum for the subset of indices A bŷ S(A) = i∈A w i Z i /F i (w i T i ). This extends the Theta sketch framework [11] to non-uniform priorities and weighted samples and allows for per item thresholds.

Improved merges for distinct counting ‡
The framework also can be used to improve merge procedures for distinct counting sketches based on coordinated samples, such as the MinCount/bottom-k sketch [15,3,11]. Given two coordinated samples with 1-substitutable thresholds T A and T B for sets A and B, one simply needs to produce a new 1substitutable threshold with T i ≤ max{T A i , T B i } to produce another distinct counting sketch. This generalizes the LCS sketch of [9] which specifically takes the max of bottom-k thresholds. Our use of arbitrary 1-substitutable thresholds also allows merges to be chained together. Figure 4 illustrates the improvement when taking the union of sets A and B of size |A| = 10 6 , |B| = 2 × 10 6 , and varying Jaccard similarity. Another scenario where improved merges can help is when one set dominates the others in size. For example, if one set has size |A 0 | = 10 6 , and there are 10 6 sets with 100 distinct items, then Theta sketches of size 100 will result in a threshold of ≈ 100/10 6 = 0.01 after merging. It will estimate the population of 101 × 10 6 with error ±1%. On the other hand, only the large sketch contributes to the error in our case. This error is ≈ 10 6 × 1%, which is 100× better than that of the Theta sketch.

Frequent items for distinct counting †
A common database aggregation computes a distinct count of items grouped by some attributes, for example, the number of distinct users that saw an ad grouped by time and demographic variables. Although each distinct counting sketch is small, the group by operation can create tens of millions of sketches, resulting in a large memory footprint. Oftentimes, many of these groups contain only a few items. Previous approaches have used counter sharing [34,31] and sparse representations for small counters [18]. We propose a novel approach use subsampling.
At any point in time, rather than maintaining a bottom-k sketch of item hashes for every group, maintain m bottom-k sketches, each associated to a single group, and one general pool of samples. For these m groups, denote the bottom-k threshold for group g by T g . For the general pool, we use the threshold For a new item x in group g, if g corresponds to one of the m bottom-k sketches, then add x to the sketch for g. Otherwise, add the item and its group to the general pool if its priority is below T max . If there are more than k items from the same group g in the general pool, then let g be the group with the largest threshold amongst the m and create a new bottom-k sketch for g using items from the general pool. Replace g 's counter with the bottom-k sketch for g, and move the items in the sketch for g into the general pool. In both cases, if the threshold T max for the general pool is reduced, discard any items with priority above the new threshold. In effect, we adjust the sampling rate to be the appropriate sampling rate for the top m groups. Equivalently, the tolerated error for a small group is raised from being a percentage of the small group's size to a percentage of the heavy hitters' group sizes.
While using a bottom-k sketch for every group forces the number of sketches to grow linearly with the number of groups, many small groups will not have any sampled items in this sketch. This alleviates the problem of having too many counters.

Multi-Stratified sampling †
Suppose a data set of users can be stratified in two ways, by country or by age. We wish to draw a single sample which is both a stratified sample by country and a stratified sample by age and fits within a budget of B items. We first show how to generate a stratified sample, and then how to control the budget.
First, maintain a bottom-k threshold τ This sample has variable size m ∈ [k max{n c , n a }, k(n c + n a )] where n c and n a are the number of distinct countries and ages. We wish to ensure the sample contains exactly B items. We modify the stopping rule for the thresholds so that k, the number of items per stratum, is dynamically selected. For a set of thresholds, choose a stratum with the most number of elements below its threshold. Decrement its threshold to the next smaller priority. Since an item belongs to more than one stratum, one for country and one for age, this may not decrease the total sample size. Continue decreasing the thresholds until the desired sample size is reached. A nearly identical argument to the bottom-k case shows that this threshold is also substitutable.

Multi-objective samples *
When using samples, the importance of an item may depend on the query. For example, an analyst may be interested in either profit or revenue. Queries on profit ideally utilize a weighted sample with weight proportional to each item's profit. Similarly, queries on revenue ideally weight by revenue. The existing approach by Cohen [6] combines two coordinated bottom-k sketches, one with weights optimized for profit and another optimized for revenue, to obtain a sketch that has size ≤ 2k. This ensures the combined sketch never does worse than an individual sketch. However, as more objectives are added, each objective's sketch must be made smaller. Given a budget constraint B and c different objectives, each objective can only be allocated a sketch with space B/c. When sketches have high overlap, the size of the combined sketch can be much less than the budget. For example, if every objective assigns highly correlated weights to each item, then the priorities are highly correlated as well. Hence, sketches for every objective are nearly the same and approximately B/c of the budget B is used after combining the sketches. In the case where weights are scalar multiples of each other, exactly B/c of the budget is used up to rounding.

Variance sized samples †
Priority sampling provides a relative error guarantee on the sum provided the weights are proportional to the values in the sum. It guarantees the variance of the error is bounded by V ( ) ≤ S 2 /(k −1) where S is the true sum and k is the sample size [27]. However, one may wish to have a guarantee on the absolute error V ( ) ≤ δ 2 , or the weights may not be proportional to the weights.
We instead set a stopping time which stops at the first threshold T where the estimated variance matches the desired error, V (Ŝ T ) ≥ δ 2 . Here,Ŝ t is the HT estimator with a fixed threshold t. The unbiased estimate of the variance of the HT estimatorV (Ŝ t ) = i 1(R i < t)x 2 i 1−wt wt 1(wt < 1) is discontinuous only at jumps when the threshold is equal to some priority. At all other threshold values, it increases continuously as t decreases. Thus, EV (Ŝ T ) = δ 2 .
We note that while processing a stream or data file, it is typically impossible to verify that a threshold is a stopping time with just the information in the sample. The stopping time may be a larger threshold that includes additional points that are not in the sample. However, since the true variance of an estimator is strictly increasing as the threshold decreases, it is reasonable to expect that all thresholds where the estimated variance equals the desired variance are close together. By slightly oversampling, one is likely able to recover the true stopping time.

Early stopping in AQP †
Rather than explicitly constructing samples, another way to use adaptive threshold sampling is to store all of the data but sort items by their priorities. Given a user specified standard error δ, an approximate query processing (AQP) system can provide an answer by using the variance sized sampling scheme given above to determine how many items need to be read and to stop processing once it has read enough.
This can also be combined with other methods to define a physical layout of the data that is appropriate for sampling. For example, one can combine it with multi-objective sampling to get a layout that is useful for multiple queries. Suppose both revenue and quantity are metrics of interest in a dataset. Denote their values for row i by s i and q i respectively and their priorities by S i = U i /s i and Q i = U i /q i . One can generate a file block consisting of a bottom-k sample ordered by S i and a bottom-k sample of the remaining items ordered by Q i . Repeating this procedure on the remaining items generates a physical layout of the data which only needs to read m blocks to get a weighted sample of size at least mk.

Asymptotic behavior
The framework we have described thus far covers unbiased estimation. This excludes a number of important estimators that are consistent but not unbiased, such as maximum likelihood estimators, quantile estimators, and more generally, any estimator which is the maximizer of an objective function. We extend our framework to justify using such estimators as well as using some heuristic thresholding rules in asymptotic settings. We also show that in asymptotic settings where the inclusion probabilities go to 0, all priority distributions are asymptotically equivalent to appropriately weighted uniform distributions used in priority sampling.
While the practical implication of this section are significant, it is largely theoretical and requires knowledge of empirical process theory. For this reason, we first provide a brief overview of the main ideas. It requires minimal prerequisite knowledge and states our main results in a easily understandable way at the cost of rigor. We then provide an overview for the theory we develop and techniques we use before stating and proving our results.

Basic Overview
The main idea is to consider adaptive thresholds that either converge to a fixed threshold with high probability or are close to it. We show in what ways they can be treated as if they were actually fixed thresholds. For example, if a thresholding rule generates a single threshold T that is used for all points, the threshold T approximates a fixed threshold t 0 if T ∈ (t 0 − , t 0 + ) with high probability (w.h.p.) for some small ≥ 0. Ifθ t is an estimator for θ for fixed thresholds t. When applied to an adaptive threshold, the error ofθ T is bounded by the worst case error |θ T − θ| ≤ sup |h|< |θ t+h − θ| for estimators on that range of thresholds.
The difficulty is that we must show that the estimate at all perturbed thresholdsθ t+h are close toθ t . This requires a notion of continuity which cannot be obtained from a pointwise variance calculation at a specific threshold. However, empirical process theory allows us to do just that.
We apply it to analyze the class of M-estimators, that is estimators that maximize an objective function formed by the sum over independent random variables. They are of the form for some function f and n i.i.d. random draws from some distribution X i ∼ P . They include maximum likelihood estimators, quantile estimators, regression estimators under L 2 or some other loss, as well as many neural networks. We extend this to obtain an objective J n (θ; t) that depends on both the parameter θ as well as the threshold t. Empirical process theory allows us to show, under the appropriate rescaling, this objective asymptotically converges to a Gaussian process as more data is encountered. Crucially, this Gaussian process has continuous paths. In other words, when treated as a function of t, the Gaussian process is a random, continuous function. Thus, convergence of the objective to a continuous function can be used to obtain convergence of the estimators. We are particularly interested in the case where the sample size grows sublinearly with the data. Here we define an appropriate scaling of the thresholds and show that regardless of how many parameters are in a priority distribution, if all priorities are non-negative and the priority density is sufficiently smooth and non-zero around 0, the resulting threshold sampler is asymptotically equivalent to a simple weighted sampling procedure where the priority distribution are just parameterized by a univariate weight. This means any priority distribution can replicated using R i ∼ Uniform(0, 1/w i ) as the priority distribution and appropriate choices of weights w i . This results in an asymptotically equivalent sampling distribution. This convergence can only be proved when the class of functions {f θ } θ used in the objective as well as the collection of thresholding functions are not too complex. Heuristically, this means they cannot be chosen to overfit the data too much.
Together these provide our main results. Loosely speaking, the first states that if (1) an estimatorθ t on deterministic thresholds is consistent and (2) an adaptive threshold T converges to a deterministic threshold in an appropriate asymptotic regime and is not overly complex, then the estimatorθ T on the adaptive threshold is also consistent. The second implies that if an adaptive threshold sample grows sub-linearly with the data and priorities are non-negative, the precise choice of priority distribution does not matter. Any priority distribution is asymptotically equivalent to using R i ∼ Uniform(0, 1/w i ) for an appropriate set of weights w i .

Technical Overview
We now present an overview of the technical details. We consider an extension of an objective function which includes a threshold as a parameter. For any priority distribution and fixed threshold t, it is easy to see that the HT-estimator of an M-estimator's objective E n f θ (X i ) can be expressed as an empirical expectation after reweighting byĴ Since our asymptotic results require an infinite sequence of points, we assume the points X i are i.i.d. draws from some distribution P x . The corresponding priority R i ∼ F (·|X i ) is drawn from some conditional distribution that depends only on X i . The threshold t(X i ) is also a function of a data point. We show that the suitably rescaled objective converges to a Gaussian process, but rather than being indexed by just the parameter of interest θ, it is indexed by both θ and the threshold t. This convergence holds when both the function class {f θ } θ and the class of thresholds T are not too complex.
This allows us to prove consistency of M-estimators under adaptive thresholding schemes. If a threshold T n converges in probability to a deterministic threshold t, then the objective under the random thresholdĴ(θ; T ) and fixed thresholdĴ(θ; t) converge to the same limit under the continuity of Gaussian processes. Hence, if an estimator is consistent under the deterministic threshold, it is also consistent under the random threshold.
Note that the threshold in this case need not be substitutable, nor does one need to be able to recalibrate it. Heuristic thresholding rules may be used as long as they converge to an appropriate limit.
We consider two asymptotic regimes, one where the adaptive thresholds converge to fixed thresholds and sample sizes grow linearly with the data, and one where the sample sizes grow sublinearly. The first case is straightforward and relies only on the closure properties of bounded uniform entropy integral function classes to prove a Donsker result that n −1/2 (J n (θ, t) − J(θ)) p → GP θ,t for an appropriate Gaussian process GP θ,t . For the latter case where the sample size grows sublinearly, we not only need to rescale the objective but also the thresholds to obtain convergence. In this regime, we show that the shape of the priority distribution is asymptotically irrelevant. The asymptotic distribution is only affected by the scaling of priorities. Given convergence of the objective, we can prove our main result Theorem 10. Letθ be an M-estimator for θ 0 under some distribution P θ0 , and suppose its objective J n (θ) = E n f θ (X i ) satisfies the conditions of the Mestimator consistency theorem 2.12 in [20]. Suppose there is a sequence of constants c n → c 0 ≥ 0 such that c n n → ∞ and thresholds T (n) ∈ T with c n T (n) p → T . If {f θ } θ and T satisfy the conditions of theorem 12 then the HT-estimate of the objectiveĴ n (θ, T (n) ) yields a consistent estimatorθ (n) Proof. Under these assumptions, theorems 12 and 11 and the continuous mapping theorem show that the HT-estimate of the objective also satisfies the the conditions of the M-estimator consistency theorem. Hence,θ (n) The basic setup for proving convergence to an empirical process starts with a class of functions F and an empirical measure P n for n random draws from some measure P . This empirical measure takes a function f ∈ F and maps it to the empirical mean where R i ∼ P . Since this is a mean, under mild regularity conditions, for any single, real-valued function f , the empirical mean P n f converges to a Gaussian random variable by the central limit theorem. Empirical processes theory allows one to show that, if the class of functions F is not too complex, then {P n f } f ∈F converges to a Gaussian process.

Empirical processes
We briefly review some theory for empirical processes to unfamiliar readers. We refer interested readers to [20] for more details. Our goal is to show for a class of functions Φ = {f θ } θ and threshold functions T , √ n Ĵ n (θ, t) − J(θ) converges weakly to a Gaussian process Ψ θ,t with Cov(Ψ θ,t , Ψ θ ,t ) = Cov(f θ (X)w t (R, X), f θ (X)w t (R, X)) for all f θ , f θ and t, t ∈ T as n → ∞. We can write this more succinctly as . Proving this convergence can be done in two steps. First, the finite dimensional distributions and the covariance can be shown to be Gaussian using the usual central limit theorem. Second, the empirical process Ψ (n) φ,t := √ n Ĵ n (θ, t) − J(θ) is shown to be asymptotically tight. Asymptotic tightness ensures that the sample paths of the process are appropriately smooth. Asymptotic tightness is the main challenge for establishing Donsker results.
In empirical process theory, a sufficient condition for proving asymptotic tightness is that the function class of interest is not too complex. There are multiple measures of complexity such as the VC-dimension, bracketing entropy , and uniform entropy. The corresponding conditions that ensure asymptotic tightness are finite VC-dimension, finite bracketing entropy integral, and bounded uniform entropy integral with integrable envelope. For each of these measures of complexity, there are known, broad classes of functions that satisfy these conditions. Donsker preservation theorems show that certain transformations of these classes preserve the conditions on the complexity. New classes of interest can often be verified to be Donsker by showing they are contained in a class that is appropriately transformed from these broad, base classes.
Of these conditions, we are most interested in function classes with finite VC-dimension, also known as a VC-class, and those with bounded uniform entropy integral with integrable envelope, known as a BUEI-class with integrable envelope. The envelope G for a class G is the function such that G(x) := sup g∈G |g(x)|. VC-dimension is the most restrictive of the notions of complexity. Any VC-class is also a BUEI-class. As the most restrictive measure of complexity, it allows for the greatest range of transformations. In particular, it allows for composition with monotone functions. BUEI-classes are of interest because a product of BUEI-classes remains a BUEI-class.

Donsker result for fixed thresholds
We first consider the case where an adaptive threshold converges to a fixed one, and the sample size grows linearly with the data.
Theorem 11. Let Φ be a BUEI-class of functions on a data point, and let T be a class of threshold functions that has finite VC-dimension. Further assume that F (t(x)) > for some > 0 and all x ∈ X . Then, f θ (X)w(R, t(X)) has bounded uniform entropy integral. Hence, where Ψ 0 θ,t is a Gaussian process indexed by f θ ∈ Φ and t ∈ T . Proof. Since T has finite VC-dimension, the composition rules for VC-classes (lemma 9.9 in [20]) give that both 1(r − t(x) < 0) and F (t(x)) generate VCclasses since the indicator and any CDF are monotone. Likewise, 1/F (t(x)) is a VC-class. Furthermore, it has a measurable envelope H(x) = 1/ since F (t(x)) > by assumption. Since VC-classes are BUEI-classes if there exists a envelope, and BUEI classes are closed under multiplication (theorem 9.15 in [20]), the class of functions {g(x)w t (r, x) : g ∈ G, t ∈ T } is a BUEI-class with envelope G·H. This establishes asymptotic tightness of the process Θ = {θ gt } g,t where θ gt is the Horvitz-Thompson estimator for Eg when using a threshold t. Since Donsker classes are preserved under multiplication by a bounded, measurable function (corollary 9.31 in [20]), G · w t is P -Donsker for any fixed t. Since P -Donsker classes are also closed under finite sums, the finite dimensional distributions of Θ converge to multivariate Gaussian distributions. Asymptotic tightness and the central limit theorem on finite dimensional distributions imply that Θ is P -Donsker.

Donsker result on sub-linear samples
In the above result, the resulting sample sizes must grow linearly with the data. We are interested in the case where the sample sizes still grows to infinity, but the inclusion probabilities go to 0. We show that under appropriate conditions, this is sufficiently well-approximated by a two-step procedure which downsamples the uniformly to obtain a sublinear number of data points and then applies threshold sampling where the inclusion probabilities are bounded away from 0 as above.
for some weights w x for all x ∈ Supp(P x ) such that M := sup x w x < ∞ and inf x w x > 0. Let Φ be a class of functions Φ = {f θ } and T a class of thresholds T satisfying the conditions of theorem 11. Further assume that the classes are uniformly bounded with t ∞ < T for all t ∈ T . Furthermore, consider alternative prior-itiesṘ i |X i = x ∼ Uniform(0, 1/w x ) and letJ n (θ, t) be the estimated objective using these priorities.
Then, for a sequence c n → 0 such that c n n → ∞, the processes as n → ∞ where Ψ θ,t ,Ψ θ,t are Gaussian processes and Ψ θ,t d =Ψ θ,t .
We first outline the proof. Rather than dealing with a fixed function class as before, these conditions require proving a Donsker result when the class of thresholds is changing with n. Bounded uniform entropy conditions also exist for this case which ensure convergence to a Gaussian process. However, when directly applied, the decreasing thresholds lead to envelopes whose integrals go to ∞. To handle that, we show that the random process can be generated in two stages: a uniform sampling stage that draws a sample with sublinear size and on the order of nc n and a second stage where the thresholds do not go to 0. The boundedness conditions ensure Donsker preservation results can be applied on this second stage and obtain convergence to a Gaussian process. We then compare the process using priorities R i with the approximating process usinġ R i and show their first two moments converge to the same limit. Hence, their Gaussian process limits must also be the same.
Proof. First, note that for any threshold t, inclusion of an item X i is equivalent to U i < F (c n t(X i )|X i ) for some U i ∼ Uniform(0, 1). Since F (c n t(x)|x) = w x c n t(x) + o(w x c n t(x)) < c n M T + c n eventually for any > 0, this inclusion event can be rewritten as two steps. First, U i < c n γ where γ := M T + and, if it passes this first stage, Ui cnγ < F (cnt(x)|x) cnγ . Note that this second stage uses the conditional distribution Ui cnγ |U i < c n γ ∼ Uniform(0, 1). The first stage of the inclusion event is a uniform Poisson sample. It thins the data by drawing i.i.d. Bernoulli(c n γ ) draws. The resulting sample of size C n is still from the same base distribution P as the original data. Thus, we have that Since C n ∼ Binomial(n, c n γ ) and nc n → ∞, it follows that Cn n 1 cnγ p → 1 and can be ignored by Slutzky's lemma.
Thus, we can instead examine the convergence of the process E Cn φ(X) 1(U <F (cnt(X)|X)/cnγ ) F (cnt(X)|X))/cnγ . Let V be the VC-index of T . The threshold {F (c n t(X)|X))/c n γ : t ∈ T } is a VC-class with index ≤ V since scalar transformations do not change the VCindex and monotone transformations composed with a VC-class do not increase the VC-index. Furthermore, since F (c n t(X)|X = x))/c n γ → w x t(x)/M T ≤ 1 and Φ is a BUEI-class that is uniformly bounded by some constant H, the empirical expectations are taken over function classes that are uniformly bounded by H. Together these imply converges to a Gaussian process limit with mean 0 as long as its finite dimensional marginals converge to multivariate Gaussians. The law of large numbers gives that nc n γ /C n → 1. Since can be arbitrarily small, equation 14 is proved. Now consider the process which replaces F (r|x) with the approximatioṅ F (r|x) = w x r. We wish to show that the mean and covariances of the process in equation 16 remain the same after the substitution. Since the HTestimator is unbiased regardless of the choice of F , the mean is 0. Let Z n = 1 U < F (cnt(X)|X) cnγ andŻ n be the same with F replaced byḞ .
Note, F (c n r|x) = c n w x r + o(c n w x r). The difference in inclusion variables weighted by the inverse pseudo-inclusion probability is ∆ n = Z n F (c n t(X)|X))/c n γ −Ż ṅ F (c n t(X)|X))/c n γ = γ w X t(X) Z n (1 + o(t(X))) −Ż n This gives |∆ n | ≤ γ w X t(X) o(1) if Z n =Ż n and |∆ n | ≤ γ w X t(X) (1 + o(1)) otherwise. Since P (Z n =Ż n ) = o(1) and both w X and t(X) are bounded away from 0, the variance V ar(∆ n ) = o(1) → 0 as n → ∞. Since Φ has integrable envelope, f θ 2 is bounded. The Cauchy-Schwartz inequality gives that covariances of the processes using F andḞ are equal. Thus,Ĵ in equation 14 can be replaced byJ while still converging to the same limit. Finally, note that when priorities are fromḞ , the two-stage sampling trick provides a means to rescale the threshold. This givesJ n (θ, αδt) d =J B (θ, δt) where B ∼ Binomial(n, α). UsingḞ in place of F and rescaling the threshold in equation 14 by c n M T yields equation 15. In the thinning stage, the role of is simply to ensure that F (c n t(X)|X) can be upper bounded by c n (M T + ). Any value of that yields an upper bound yields exactly the same process in the end. SinceḞ (c n t(X)|X) ≤ M T already, can be set to 0.
Although the condition on the CDFs requiring a linear expansion near 0 may appear restrictive, we note that it is satisfied under reasonable settings. If the priorities are drawn from conditional densities f (·|X) that are differentiable in a neighborhood [0, δ) with δ > 0 and if f (0|·) is both upper bounded and bounded away from 0, then a Taylor expansion ensures the condition is satisfied. For example, if f (·|x) is the Uniform(0, 1/x) density associated with priority sampling or an Exponential(x) density, then the condition is satisfied if x can be bounded. Furthermore, even if the original CDF does not have a linear expansion, a monotone transformation of the priorities may be able to convert the priorities into ones where the CDF has a linear expansion. The following lemma shows that if the ratio of CDFs for priorities has a limit at 0 then they are asymptotically equivalent to using Uniform priorities, where the CDFs do have a linear expansion.
Lemma 13. Consider priorities R i taking values in the non-negative reals. Further suppose their conditional distributions F (·|x) are continuous in a neighborhood of 0 with F (0|x) = 0 and there exists constants w x with inf x w x > 0 such that for δ → 0 + sup x,y There exist independently drawn priorities with conditional distributionṘ i |X i = x ∼ Uniform(0, 1/w x ) and a monotone transformation ρ such that p(1(Ṙ i < t) = 1(ρ(R i ) < t)) = o(t).
Proof. The conditions imply sup x |F (δ|x) − α x η(δ)| = o(η(δ)) by taking η(δ) = α −1 y F (δ|y) for some fixed y. Since η is increasing and continuous in a neighborhood of 0, for sufficiently small b we can simply rescale the priorities to obtaiñ R i = bη −1 (R i ) if R i ∈ [0, b) andR i = R i otherwise. This defines the function ρ. Denote the CDF of a Uniform(0, 1/w x ) distribution asḞ (r|x) = w x r. The prioritiesR i =F −1 (U i |X i ) andṘ i =Ḟ −1 (U i |X i ) can be obtained from the inverse probability transform for their corresponding CDFs. Thus, the indicators are not equal only ifḞ (t|X i ) ≤ U i <F (t|X i ) orF (t|X i ) ≤ U i <Ḟ (t|X i ). Each of these happen with probability less than sup x |F (t|x) −Ḟ (t|x)| = o(t).

Applications of asymptotic theory
While we have already shown that the asymptotic theory justifies the re-use of consistent estimators for Poission sampling, we can also use it to justify the use of heuristically constructed thresholds.
Consider again the problem of building a sample that can provide an absolute variance guarantee. Recall that in section 3.9, it is not sufficient to choose a threshold where the estimated variance is equal to the target variance. Additional points must be sampled to ensure that the chosen threshold is the largest of such thresholds. This added layer of complexity can be removed by applying the asymptotic theory to show that the heuristically constructed threshold without oversampling still leads to consistent estimators.
Our Donsker result show that the HT variance estimate in 7 after centering and rescaling V ar(θ t ) ≈ V ar(θ t )) + Ψ t / √ n where Ψ t is a zero-mean Gaussian process. Since V ar(θ t )) is increasing with t and the error term Ψ t / √ n is decreasing with n, if the variance estimator's variance is not too large, then a Gaussian maximal inequality can be used to show the heuristically chosen threshold without the additional oversampling step is close to the threshold with the desired variance.

Future work and Conclusion
We have provided a general framework for building sampling schemes that adapt to the data on the fly and satisfy system constraints while behaving similarly to fixed thresholds. This simplifies creating new sampling schemes while making the resulting sampled data sets easy to analyze. This framework unifies a long line of research on bottom-k sampling.
We demonstrate its usefulness by providing sampling schemes that can solve a variety of existing and new problems. These include engineering problems of fitting within system and budgetary constraints, usability problems that allow users to tune the desired accuracy for AQP results at query time, and novel problems such as top-k queries. This flexibility in the framework can make it more useful in practice, by making it easier to design systems and satisfy user requirements. At the same time, it ensures that the same estimators used for fixed thresholds can also be used for adaptive thresholds, making it easy to code just one set of estimators while the underlying sampling schemes can be easily changed. Furthermore, these are just a few examples that apply the framework. Future work expands on other potential applications that can be solved with this sampling framework.