Alias table sampling
These notes, from a short talk at GDL Origami in March 2022, present the alias table, a structure that samples a discrete distribution in constant time, and compare it with classic discrete cdf inversion.
- What is an alias table?
- Discrete CDF
- Alias tables
- Alias table construction
- Alias table interface
- Performance
- Two-step parallel construction
- Single-pass sampling of a stream: reservoir and bidirectional CDF sampling
- Takeaway
- References
What is an alias table?
An alias table is a structure to sample discrete distributions, the simplest of which is a fair die, where every face has probability \(\frac{1}{6}\). A loaded die favors some faces; here the six comes up five times more often than the others:
| face | ⚀ | ⚁ | ⚂ | ⚃ | ⚄ | ⚅ |
|---|---|---|---|---|---|---|
| fair die: weight | 1 | 1 | 1 | 1 | 1 | 1 |
| fair die: probability | \(\frac{1}{6}\) | \(\frac{1}{6}\) | \(\frac{1}{6}\) | \(\frac{1}{6}\) | \(\frac{1}{6}\) | \(\frac{1}{6}\) |
| loaded die: weight | 1 | 1 | 1 | 1 | 1 | 5 |
| loaded die: probability | \(\frac{1}{10}\) | \(\frac{1}{10}\) | \(\frac{1}{10}\) | \(\frac{1}{10}\) | \(\frac{1}{10}\) | \(\frac{1}{2}\) |
More generally, we want to pick one item among \(A, B, C, D, E, \dots\) with probabilities proportional to their weights \(w_A, w_B, w_C, w_D, w_E, \dots\), as needed in:
- importance sampling,
- simulations, data analysis, machine learning, statistics, etc.
Discrete CDF
The classic way to sample a discrete distribution is to invert its cumulative distribution function (cdf). We use this example throughout:
| item | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| weight | 7 | 3 | 4 | 1 | 6 | 3 |
Discrete CDF inversion
To pick an item, draw a uniform random number \(u \in [0, 1)\) and select the first item whose cdf is at least \(u\): since the cdf is sorted, this is a binary search in \(O(\log n)\).
Discrete CDF implementation
struct DiscreteCDF
{
int n;
float total;
std::vector<float> cdf;
DiscreteCDF(const std::vector<float>& values) : n(values.size()), total(0), cdf(n)
{
for(int i = 0; i < n; ++i)
{
total += values[i];
cdf[i] = total;
}
}
int sample(const float u)
{
const float value = u * total;
int p = 0, q = n - 1;
while(p < q)
{
int m = (p+q) / 2;
if(cdf[m] < value)
p = m + 1;
else
q = m;
}
return p;
}
};
In rendering, discrete cdfs sample areas (lights), images (environment maps), volumes, etc.
| Discrete CDF | |
|---|---|
| construction | \(O(n)\) |
| sampling | \(O(\log n)\) |
Alias tables
An alias table also samples a discrete distribution with weights \(w_A, w_B, w_C, \dots\), but in constant time!
Alias tables have regained attention recently:
- New fast method for generating discrete random numbers with arbitrary frequency distributions, A. J. Walker, 1974
- A linear algorithm for generating random numbers with a given distribution, M. D. Vose, Software Engineering, 1991
- Parallel Weighted Random Sampling, L. Hübschle-Schneider and P. Sanders, 2019 - 2021
- Weighted Random Sampling on GPUs, H.-P. Lehmann, L. Hübschle-Schneider and P. Sanders, 2021
- The alias method for sampling discrete distributions, C. Wyman, Ray Tracing Gems II, Chapter 21, 2021
- used in the implementation of the ReSTIR algorithm [Bitterli et al. 2020]
| Discrete CDF | Alias [Walker] | Alias [Vose] | Alias [Hübschle] | Bidirectional CDF [Ciklabakkal] | |
|---|---|---|---|---|---|
| construction | \(O(n)\) | \(O(n^2)\) | \(O(n)\) | \(O(n)\) | none |
| sampling | \(O(\log n)\) | \(O(1)\) | \(O(1)\) | \(O(1)\) | \(O(n)\) |
| memory | \(O(n)\) | \(O(n)\) | \(O(n)\) | \(O(n)\) | \(O(1)\) |
The last column, a single-pass method for weights that are not stored, is covered at the end of these notes.
Alias table construction
We build the alias table of our example; the construction applies to any real weights or frequencies, not only integers. The idea is to rearrange the weights into \(n\) columns whose height is the mean weight, each holding at most two items:
- compute the mean,
- large items have a weight > mean,
- small items have a weight <= mean,
- split the large items and share their residuals with the small ones [Hübschle-Schneider and Sanders 2019].
The required operations are:
- find the next small item,
- find the next large item,
- pack a small item,
- pack a large item.
Each column stores a split, the fraction owned by its own item, and an alias, the item that fills the rest:
| label | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| split | 1 | 0.75 | 1 | 0.25 | 0.5 | 0.75 |
| alias | A | E | A | E |
An item can spread over several columns: A owns its column, a quarter of B’s and half of E’s, so it is picked with probability \(\frac{1}{6}\left(1 + 0.25 + 0.5\right) = \frac{7}{24}\), as expected. The table is not unique: the code below visits the items in another order and builds a different valid one (A: split 0.75, alias E; D: split 0.25, alias A; E: split 1).
Alias table interface
struct Alias
{
float t; // split
int i; // alias
};
struct AliasTable
{
int n;
std::vector<Alias> table;
AliasTable(const std::vector<float>& values);
int sample(const float u);
};
The construction fits in about 40 lines, with two temporary arrays and three loops in \(O(n)\). The splits are accumulated in double precision: in float, the running residuals drift on large tables.
AliasTable::AliasTable(const std::vector<float>& values) : n(values.size()), table(n)
{
const double sum = std::accumulate( values.begin(), values.end(), 0.0 );
const double avg = sum / n;
std::vector<double> t(n);
std::vector<int> partition(n);
int lid = 0, hid = n-1;
for(int i = 0; i < n; ++i)
{
t[i] = values[i]/avg;
if( t[i] <= 1 )
partition[lid++] = i;
else
partition[hid--] = i;
}
lid = 0, hid = n-1;
int tlid = partition[lid], thid = partition[hid], nthid;
// construct alias table
while(lid < hid)
{
if( t[thid] > 1 )
{
table[tlid].i = thid;
t[thid] -= (1 - t[tlid]);
tlid = partition[++lid];
}
else
{
nthid = partition[--hid];
table[thid].i = nthid;
t[nthid] -= (1 - t[thid]);
thid = nthid;
}
}
// last item should have 100% chance to be picked
t[thid] = 1;
table[thid].i = std::numeric_limits<int>::max();
for(int i = 0; i < n; ++i)
table[i].t = float(std::min(std::max(t[i], 0.0), 1.0));
}
Sampling is \(O(1)\) in 3 lines: the integer part of \(n \cdot u\) selects a column uniformly, and its fractional part chooses between the column’s item and its alias.
int AliasTable::sample(const float u)
{
const int id = n * u;
const float u2 = n * u - id;
return u2 < table[id].t ? id : table[id].i;
}
Performance
Two-step parallel construction
- divide and conquer approach,
- split the array into \(p\) subproblems,
- a subproblem is determined by finding triplets \((i, j, s)\) such that:
The light items \(\ell\) and heavy items \(h\) are stored in two arrays, in sweep order. The first \(n'\) columns hold the first \(i\) light items, the first \(j\) heavy items, and a share \(s\) of the next heavy item \(h[j+1]\), the spill. The bound \(n' \cdot \frac{W}{n}\) is the weight of \(n'\) columns (the slides wrote \(p \cdot \frac{W}{n}\); the figure below uses \(n' = 7\) and \(n' \cdot \frac{W}{n} = 70\)). The \(k\)-th split takes \(n' = \lfloor k \, n / p \rfloor\), giving each part about \(n / p\) columns. Since \(\sigma\) decreases as \(i\) grows and \(j = n' - i\) shrinks (a light item weighs less than a heavy one), the split is found by binary search on \(i\) over prefix sums of the light and heavy weights. Each part then runs the sequential sweep on its own items, independently: its first heavy item has already given \(s\) to the previous part, and the spill fills its last light columns.
A minimal implementation with the same table layout as AliasTable (alias_parallel.h):
// Two-step parallel alias table construction [Hübschle-Schneider and Sanders 2019].
// Same table layout as alias.h: table[k].t is the split of column k, table[k].i its alias.
// Requires at least one item and a positive total weight.
#include "alias.h"
#include <thread>
struct ParallelAliasTable
{
int n;
std::vector<Alias> table;
ParallelAliasTable(const std::vector<float>& values, int p) : n(values.size()), table(n)
{
// normalized weights (mean 1), light (t <= 1) and heavy (t > 1) items with prefix sums
const double avg = std::accumulate(values.begin(), values.end(), 0.0) / n;
std::vector<double> t(n), L{0}, H{0};
std::vector<int> light, heavy;
for(int k = 0; k < n; ++k)
{
t[k] = values[k] / avg;
if(t[k] <= 1) { light.push_back(k); L.push_back(L.back() + t[k]); }
else { heavy.push_back(k); H.push_back(H.back() + t[k]); }
}
const int nl = light.size(), nh = heavy.size();
// step 1: split the n columns into p parts. The first m = n' columns hold the first i light
// and j = m - i heavy items, plus a spill s = m - (L[i] + H[j]) from heavy item j.
// i is the first index with L[i] + H[m - i] <= m (n' * W/n with normalized weights),
// found by binary search since L[i] + H[m - i] decreases with i.
struct Split { int i, j; double s; };
p = std::max(1, std::min(p, n));
std::vector<Split> split(p + 1, {0, 0, 0.0});
for(int k = 1; k <= p; ++k)
{
const int m = (long long)n * k / p;
int lo = std::max(0, m - nh), hi = std::min(nl, m);
while(lo < hi)
{
const int mid = (lo + hi) / 2;
if(L[mid] + H[m - mid] <= m) hi = mid; else lo = mid + 1;
}
split[k] = {lo, m - lo, m - (L[lo] + H[m - lo])};
}
// step 2: run the sequential sweep on each part independently.
// Part k packs lights [i_k, i_k+1) and heavies [j_k, j_k+1); its first heavy already gave
// s_k to part k-1, and heavy j_k+1 (the spill) fills the remaining light columns.
auto sweep = [&](int k)
{
int i = split[k].i, j = split[k].j;
const int iend = split[k + 1].i, jend = split[k + 1].j;
double w = (j < nh ? t[heavy[j]] : 0) - split[k].s; // residual of heavy j
while(i < iend || j < jend)
{
if(i < iend && (j == jend || w > 1)) // pack a light column
{
table[light[i]] = {float(t[light[i]]), j < nh ? heavy[j] : light[i]};
w -= 1 - t[light[i]];
++i;
}
else // pack a heavy column
{
const bool last = j + 1 == nh;
table[heavy[j]] = {float(w), last ? heavy[j] : heavy[j + 1]};
w = (last ? 0 : t[heavy[j + 1]]) - (1 - w);
++j;
}
}
};
std::vector<std::thread> threads;
for(int k = 0; k < p; ++k) threads.emplace_back(sweep, k);
for(auto& thread : threads) thread.join();
}
int sample(const float u) const
{
const int id = n * u;
const float u2 = n * u - id;
return u2 < table[id].t ? id : table[id].i;
}
};
The parts write disjoint columns, so the final join is the only synchronization. On our example, every \(p\) builds the same table as the sequential code.
Single-pass sampling of a stream: reservoir and bidirectional CDF sampling
Sampling a stream of weights
Both structures above are built once and sampled many times. In resampling (RIS, ReSTIR), the \(M\) candidates are generated on the fly, for instance per pixel, and we want to pick one proportionally to its weight without storing them or building a table.
Weighted reservoir sampling does this in one pass with constant memory, at the cost of one random number per candidate: it keeps one candidate and replaces it by candidate \(k\) with probability \(w_k / \sum_{i \le k} w_i\) (see the weighted reservoir sampling section of my notes on importance sampling).
Bidirectional CDF sampling
Ciklabakkal et al. [2022] proposed a single-pass algorithm that returns the same index as cdf inversion for the same \(u\). It reads the candidates from both ends, summing the weights seen from the front, \(\overline{w}_{front}\), and from the back, \(\overline{w}_{back}\). Each step advances the front if \(\overline{w}_{front} \le u \cdot (\overline{w}_{front} + \overline{w}_{back})\) and moves the back otherwise, until the two indices meet:
// Bidirectional CDF sampling [Ciklabakkal et al. 2022, Algorithm 1].
// weight(k) returns the weight of candidate k in [0, n). Requires n > 0, u in [0, 1)
// and a positive total weight.
template <typename Weight>
int bidirectional_cdf_sample(const Weight& weight, const int n, const float u)
{
int front = 0, back = n - 1;
double wfront = weight(front), wback = weight(back); // running sums from both ends
while(front != back)
{
if(wfront <= u * (wfront + wback))
wfront += weight(++front);
else
wback += weight(--back);
}
return front;
}
The paper proves (Appendix A) that every step keeps the invariant \(\sum_{i < front} w_i \le u \cdot W < \sum_{i \le back} w_i\), with \(W\) the total weight. When \(front = back = j\), this is \(\sum_{i < j} w_i \le u \cdot W < \sum_{i \le j} w_i\): the index selected by cdf inversion, although \(W\) is never computed beforehand. The cost is one pass of \(n - 1\) steps, one weight evaluation per candidate (the meeting one is read twice), a single random number and \(O(1)\) memory. The candidates must be readable from both ends, which the paper notes is rarely limiting in rendering, where a candidate can be generated from its index. Since the traversal depends on \(u\), a pass gives a single sample: for \(N\) samples, the paper takes one from each of \(N\) subsets of the \(M\) candidates, and shows that this has lower variance than drawing \(N\) samples from the whole set.
This code (bidirectional_cdf.h) matches DiscreteCDF except on exact ties, where \(u \cdot W\) equals a prefix sum: it then skips to the next item with positive weight, while DiscreteCDF can return a zero-weight item.
Why cdf inversion keeps stratification, and alias tables don’t
Cdf inversion is monotone: item \(i\) is selected exactly when \(u \in [P_{i-1}, P_i)\), with \(P_i\) the cdf. With \(N\) stratified \(u\), one in each \([\frac{k}{N}, \frac{k+1}{N})\), the prefix \([0, P_i)\) contains \(\lfloor N P_i \rfloor\) full strata and at most one partial stratum, holding at most one point. The first \(i\) items thus receive \(\lfloor N P_i \rfloor\) or \(\lceil N P_i \rceil\) samples, and each item count differs from \(N p_i\) by less than 2, for any \(N\). Moreover, close values of \(u\) give close indices.
An alias table maps \(u\) to a column \(\lfloor n u \rfloor\) and to \(u_2 = n u - \lfloor n u \rfloor\). Item \(i\) is selected on its own part of column \(i\) and on the alias parts of other columns: a union of \(m_i\) intervals of \(u\), ordered by the construction rather than by item. The same argument on each interval bounds the count error by \(2 m_i\) instead of 2, and neighboring values of \(u\) can land on unrelated items: the item order along \(u\) is lost.
Bidirectional CDF sampling returns the cdf inversion result, so it keeps this property in a single pass. Reservoir sampling draws one random number per candidate and loses the stratification of \(u\): this motivates the paper, whose Figure 1 shows that neither of two reservoir variants keeps it.
Stratified indices give stratified points in the domain only if close indices are close points. The paper orders the candidates along a Hilbert curve, \(y_k = \text{Hilbert}\left(\left\lfloor \frac{k}{M} 2^{dm} \right\rceil\right)\) over a \(2^m\) grid of the \(d\)-dimensional unit hypercube, which keeps neighbors on the curve close in the hypercube. Stratified \(u\) then give stratified samples in primary sample space, though the paper notes this may not carry over to the integration domain in higher dimensions.
The table below measures both effects with the same jittered stratified \(u\), against independent random \(u\). In 1D, on our example (\(7, 3, 4, 1, 6, 3\)), the error is the largest \(\lvert \text{count}_i - N p_i \rvert\) over the items (mean / worst over \(N = 1 \dots 256\)). In 2D, a Gaussian over a \(32 \times 32\) grid ordered along a Hilbert curve is sampled with \(N = 256\), and the error is the largest deviation of the sample count in \(4 \times 4\) blocks of cells (mean).
| 1D example, stratified \(u\) | 1D example, random \(u\) | 2D grid, stratified \(u\) | 2D grid, random \(u\) | |
|---|---|---|---|---|
| cdf inversion | 0.81 / 1.83 | 6.40 / 23.0 | 1.03 | 9.41 |
| alias table | 1.08 / 3.25 | 6.41 / 26.0 | 4.15 | 9.07 |
With six items, none has more than three pieces in the alias table, and the counts stay close to the cdf’s. In 2D, where the order of the cells matters, the alias table keeps only part of the stratification gain.
Takeaway
- Static weights, sampled many times (environment maps, many lights): build a structure once. The discrete cdf is the simplest, with \(O(\log n)\) sampling; the alias table samples in \(O(1)\), faster at every size measured, at a higher but parallelizable construction cost that is recovered after a fraction of \(n\) samples.
- Stratified or low-discrepancy samples (QMC, blue noise): prefer cdf inversion, with items ordered so that close indices are close in the domain (e.g. along a Hilbert curve); the alias table loses the item order and keeps only part of the stratification.
- Weights streamed once (resampling candidates generated on the fly): no table. Reservoir sampling needs one pass in any order, but one random number per candidate, and loses stratification. Bidirectional CDF sampling reads the candidates from both ends and returns the cdf inversion result, so it keeps the stratification of \(u\); for \(N\) samples, split the candidates into \(N\) subsets.
| Discrete CDF | Alias table | Reservoir sampling | Bidirectional CDF | |
|---|---|---|---|---|
| construction | \(O(n)\) | \(O(n)\), parallel | none | none |
| sampling | \(O(\log n)\) | \(O(1)\) | \(O(n)\), \(n\) random numbers | \(O(n)\), 1 random number |
| memory | \(O(n)\) | \(O(n)\) | \(O(1)\) | \(O(1)\) |
| single pass over a stream | no | no | yes | yes, from both ends |
| keeps the stratification of \(u\) | yes | partly | no | yes |
References
- A. J. Walker, New Fast Method for Generating Discrete Random Numbers with Arbitrary Frequency Distributions, Electronics Letters 10(8), 1974.
- M. D. Vose, A Linear Algorithm for Generating Random Numbers with a Given Distribution, IEEE Transactions on Software Engineering 17(9), 1991.
- L. Hübschle-Schneider, P. Sanders, Parallel Weighted Random Sampling, ACM Transactions on Mathematical Software 48(3), 2022 (preprint, 2019).
- H.-P. Lehmann, L. Hübschle-Schneider, P. Sanders, Weighted Random Sampling on GPUs, arXiv preprint, 2021.
- C. Wyman, The Alias Method for Sampling Discrete Distributions, Ray Tracing Gems II, Chapter 21, Apress, 2021.
- B. Bitterli, C. Wyman, M. Pharr, P. Shirley, A. Lefohn, W. Jarosz, Spatiotemporal Reservoir Resampling for Real-Time Ray Tracing with Dynamic Direct Lighting, ACM Transactions on Graphics 39(4) (SIGGRAPH), 2020.
- E. Ciklabakkal, A. Gruson, I. Georgiev, D. Nowrouzezahrai, T. Hachisuka, Single-Pass Stratified Importance Resampling, Computer Graphics Forum 41(4) (EGSR), 2022 (project page).
- M. Pharr, W. Jakob, G. Humphreys, Physically Based Rendering: From Theory to Implementation, 3rd edition, Morgan Kaufmann, 2016.