Exact Uniform Spanning Trees as Parallel Array Operations

Sampling a spanning tree uniformly at random from a graph is the job of the textbook random-walk algorithms of Aldous-Broder and Wilson. A spanning tree is a cycle-free subset of edges that touches every vertex. These algorithms are cheap in theory and slow in practice in the languages where machine learning code lives. Python executes each random-walk step as a separate trip through its interpreter, and these steps are scalar, sequential and pointer-chasing, which is exactly the regime where interpreted overhead is worst. This note proposes to restate Wilson's algorithm so that it never takes individual walk steps. Each vertex holds one random outgoing pointer. In every round, all cycles formed by these pointers are found and re-randomized simultaneously with whole-array operations, until only a tree pointing to the root remains. A classical theorem about Wilson's algorithm, that cycles can be removed in any order without changing the output distribution, means this lockstep version is still exactly uniform. Its cost is then set by the number of rounds, not the number of walk steps.

The practical claim is that this turns UST sampling into a few dozen tensor operations per round in NumPy or PyTorch, with no compiled extension needed. It can also batch thousands of independent trees on a GPU. The scientific claim is narrower and testable. Under parallel cycle popping, the total work is identical in distribution to Wilson's step count, and only the depth (the number of sequential rounds) changes. This gives a new reading of the two-stage seeding idea of Nunes, Iacobelli & Figueiredo: a good initial subtree should reduce rounds, not just steps, and rounds are what an array runtime pays for.

Core Claim

Wilson's algorithm has an equivalent "cycle popping" description. Imagine each non-root vertex owning an infinite stack of independent random neighbor choices. The top of each stack defines a pointer graph in which every vertex has exactly one outgoing edge. Whenever that graph contains a cycle, the cycle's vertices discard their top choice. When no cycle remains, the pointers form a spanning tree directed to the root. That tree is uniform, and the set of discarded cycles does not depend on the order in which they were discarded. Cycles in a one-pointer-per-vertex graph are vertex-disjoint, so discarding all of them at once is a legal ordering. Each round therefore needs only three operations, and all three vectorize. The first draws fresh neighbors for the vertices that need them. The second detects which vertices lie on cycles, using pointer doubling: repeatedly replace each pointer by its pointer's pointer, which takes about $\log_2 n$ gather operations. The third masks the cycle vertices for redrawing.

The quantity that governs wall-clock time in an interpreted array language is

$$T \approx R \cdot (c_{\text{round}} + c_{\text{detect}} \log_2 n),$$

where $R$ is the number of popping rounds, $c_{\text{round}}$ is the fixed dispatch cost of one array operation, and $c_{\text{detect}}$ is the cost of one pointer-doubling gather. The total number of random draws equals Wilson's step count, which Nunes et al. analyze. The sequential depth $R$ has, as far as the file shows, never been measured. Whether $R$ grows slowly (polylogarithmically) or like a hitting time on hard topologies such as grids is the central open empirical question.

Relation to Prior Work

Three works define the starting point. Nunes et al. prove that Aldous-Broder and Wilson are equivalent in law at certain stopping times on complete graphs. They introduce a two-stage scheme that seeds Wilson with an unbiased subtree, with the Edge-Wilson variant seeding from one random edge. They measure only walk steps, about 7,113 versus 9,210 on the hypercube $Q_{12}$. We reuse their seeding idea as a way to reduce depth rather than steps, and we supply the missing wall-clock measurements. Zmigrod, Vieira & Cotterell compare Wilson with rejection for the single-root constraint against a Colbourn matrix-tree sampler on complete graphs. They report log-log runtime slopes of 1.14 versus 1.42. This motivates our work, since random walks win asymptotically even against BLAS-backed linear algebra. It also constrains us, because their directed, root-constrained setting must also be handled. Cycle popping works for rooted arborescences in directed graphs, and we inherit their rejection step. Hu, Lyons & Tang show that last-exit trees are also uniform. This is a reminder that several exact samplers share the same combinatorial core. We do not use their method directly.

On the runtime side, Zejun et al. show that small bytecode costs per operation dominate real Python code. AlgoTune shows that automated optimizers get about a 1.72x average speedup, mostly by adding Numba or Cython decorators, and rarely restructure algorithms. Both papers motivate the proposal. Our contribution is the kind of restructuring AlgoTune reports agents failing to find: it removes the per-step loop instead of compiling it. Approximate samplers, namely Kelner & Madry and the quantum down-up walks of Apers et al., are out of scope because we target exact samples.

Research Program

The first step is building the sampler in PyTorch and in NumPy over a compressed adjacency format (CSR, a flat array layout for graphs). Each of these versions comes in single-tree and batched form, with $B$ independent trees stored as a $B \times n$ pointer tensor. Supporting non-uniform edge weights takes one extra sampling operation. The second step is exactness verification. On small graphs, all spanning trees can be counted with the matrix-tree theorem, so a chi-square test against the uniform distribution is possible. On large graphs, edge inclusion frequencies can be checked against effective resistances, a quantity from treating the graph as an electrical circuit that gives the exact probability each edge appears.

The third step is measuring $R$ as a function of $n$ on complete graphs, hypercubes, 2D and 3D grids, Erdős–Rényi graphs and expanders, and fitting its growth. This step also sets the theoretical question: bound $R$ in terms of the maximum number of times any single vertex is popped, which cycle popping fixes in law. The fourth step is testing seeding. One option starts the pointer graph with the root plus a seed subtree $Y$, using Edge-Wilson on transitive graphs and a short vectorized Aldous-Broder prefix elsewhere. The other starts from the root alone. We then measure the change in $R$. A larger seed shortens the paths that still need to resolve, so we expect a larger reduction in $R$ than the roughly 25% reduction in steps that Nunes et al. report.

Baselines

The naive reference point is a pure-Python Wilson sampler over dictionary adjacency lists, in the NetworkX style that AlgoTune uses as reference code. It represents what practitioners run today. It will be timed on the same graphs and machine.

The strongest single-tree competitor is Wilson compiled with Numba over the same CSR arrays, using an integer successor array and the usual implicit loop erasure. This is the honest version of "just JIT it." We will tune it with the same effort as our own code. Within one process, it gets the same thread count as our CPU version, through prange over trees in batch mode. Beating it on CPU for a single tree is not expected and not claimed. Our version counts as beating it if it delivers more trees per second at batch sizes of 256 or more on GPU, or matches it on CPU without a compiler dependency. For the batched Numba version, no reported result found on Lacuna. In fact no wall-clock UST number of any kind appears in the file, so all of these measurements are new.

The strongest existing method on the directed, root-constrained dependency task is Zmigrod et al.'s pair of wilson_rc and the Colbourn matrix-tree sampler. The reported reference numbers are the log-log runtime slopes of 1.14 (Wilson) and 1.42 (Colbourn) in Zmigrod et al.. We will reimplement both on the same complete digraphs, with the Colbourn version on GPU linear algebra. Our sampler beats them if its slope is at or below 1.14 and its absolute time is lower across the sentence lengths studied.

Two ablations isolate the key ingredient. The first is a lockstep batched Aldous-Broder, in which $B$ walkers each take one step per array operation. It is exact and trivially vectorized, but its depth equals the cover time. Comparing it with our sampler tests whether cycle popping specifically, and not just batching, is what pays. The second ablation runs cycle popping sequentially, one cycle per round, which separates the parallelism from the formulation. A final ablation turns seeding on and off.

Why not just…?

Why not just compile Wilson with Numba? This is the real threat. For one tree on a CPU, a compiled sequential loop over flat arrays will likely win, because it does Wilson's minimal work with no $\log n$ cycle-detection overhead. We concede that regime. The proposal targets batched sampling inside GPU tensor pipelines, such as data augmentation for graph neural networks or sampling dependency structures during training. In those pipelines, moving data to a CPU compiler is the cost, and AlgoTune's evidence suggests that surface-level compilation is what tools usually stop at. The batched comparison against Numba will locate the crossover in batch size and graph size. If Numba wins everywhere, that is a publishable negative result.

Why not just use the matrix-tree theorem with fast linear algebra? Matrix-tree samplers are already array-native and exact. However, they cost $O(N^3)$, and Zmigrod et al. measured them scaling worse than Wilson (slopes of 1.42 versus 1.14). Our Colbourn baseline will show whether a GPU shifts that crossover for small $N$, as in short sentences. If it does, we will report the range where it wins.

Why not just batch Aldous-Broder walkers? This option is simpler than ours, but its sequential depth is the cover time, about $n \ln n$ even on $K_n$ by Nunes et al. and far larger on grids. The ablation measures this directly. If measured $R$ for cycle popping turns out comparable to cover time on grids, the advantage disappears on those topologies, and we will say so.

Decisive Checks

The idea stands or falls on three measurements. First, exactness must pass the chi-square and effective-resistance tests on every topology. Second, the growth of $R$ must stay well below cover time on $K_n$, $Q_{12}$ and grids up to $10^6$ vertices. Third, batched GPU trees per second must exceed batched Numba at realistic batch sizes, and on the Universal Dependencies-style directed task the scaling slope must be at or below 1.14. If $R$ grows like a hitting time on grids, the method is limited to well-connected graphs. In that case the seeding experiment becomes the main contribution, because it shows whether a seed tree can recover the lost depth.