Table of Contents

Lately, my favourite statistical test is permutation testing. I find it to be one of the most intuitive and powerful ways to test a frequentist hypothesis.

The fundamental idea behind permuation is rather simple: given two groups and a comparison statistic, randomly shuffle the samples between the groups and observe how the statistic changes. If there is a statistically significant difference between the groups, then randomly shuffling them should make the comparison statistic less extreme, while if there is no difference the statistic should remain relatively static.

That’s it! Rather than computing test statistic analytically, we can perform a computational test that is much more intuitive, and allows for arbitrary test statistics. The catch is that this simplicity comes with a significant computational cost. In particular, for $n$ data points, we need to perform $2^n$ calculations. This is obviously intractable for any reasonably sized dataset.

In this article, we’ll build a paired permutation test from first principles, show various python optimizations to make it run faster, and look at a statistical trick that helps us avoid the $2^n$ compute blowup.

Permutation Testing

Ultimately, we want to compare two groups with different treatments, and conclude whether the difference is statistically significant or not. We observe the control group $A$, and the intervention group $B$, with $N$ matched observations in each. For example, each pair might represent the errors of two machine learning models evaluated on the same dataset.

We then need to choose a comparison statistic, which can really be any function of the two groups:

$$ T = F(A, B) $$

For example, a typical comparison statistic would be the difference of the group means

$$T_{obs}=\frac{1}{N}\sum_{i=1}^N(B_i-A_i).$$

However, another statistic which is just as valid could be the ratio of the variances

$$T_{obs}=\frac{Var(A)}{Var(B)}$$

This gives us a lot of flexibility to implement whatever type of comparison we might want for our use cases. For example, I might want to compare the mean accuracy of models, but also some lower/upper quantile as a proxy for the worst-case accuracy. I might also want to test some ranking or proportion of the time that one model is better than the other. All of these are allowed, and simply require implementing a custom statistic.

Paired vs unpaired tests

Given the two groups $A$ and $B$, we can make a paired test, or an unpaired test. In the unpaired case, we simply randomly shuffle the datapoints between the two groups. Conversely, in the paired setting, we need to preserve the pairing rather than pooling all observations and redistributing them arbitrarily.

Permutation Swapping

For example, this interactive demo shows the shuffling of two groups $A$ and $B$ in the paired setting. Note the paired data points (shown by the pale grey lines), and how the swapping ensures that the pair of datapoints is always split between the two groups.

Exact Testing of the Null Hypothesis

In order to perform the permutation test, we need to choose two elements up front: 1) the hypothesis and 2) the test statistic.

As an example, we might want to test if the mean of group $B$ is larger than the mean of group $A$.

Given the hypothesis and the test statistic, calculating the p value is relatively straight forward. We calculate the statistic $T$ for all possible permutations of the dataset. To get the p value, we then calculate what proportion of permutations yield a test static more extreme than the statistic of the inital group.

note: Depending on the choice of statistic, you can implement a one-sided or a two sided test. for example, using the difference of group means yields a one sided test (is B larger than A), while using the absolute value of the group differences would yield a two-sided test (is B different than A).

We can implement this exact test relatively easily in python:

from itertools import product, combinations
import numpy as np

def paired_exact_test(a, b, statistic):
    a, b = np.asarray(a), np.asarray(b)
    n = len(a)

    # Calculate the original test statistic
    observed = statistic(a, b)

    hits = 0
    total = 0

    # Enumerate all possible within-pair swaps
    for mask in product((False, True), repeat=n):
        perm_a = np.where(mask, b, a)
        perm_b = np.where(mask, a, b)

        # Calculate the permuted test statistic
        permuted = statistic(perm_a, perm_b)

        # Is the permuted statistic at least as extreme?
        if permuted >= observed:
            hits += 1

        total += 1

    # Proportion of permutations at least as extreme
    p_value = hits / total

    return p_value

def unpaired_exact_test(a, b, statistic):
    a, b = np.asarray(a), np.asarray(b)
    n, m = len(a), len(b)

    # Calculate the original test statistic
    observed = statistic(a, b)

    # Pool observations from both groups
    pooled = np.concatenate((a, b))

    hits = 0
    total = 0

    # Enumerate all possible group assignments
    for indices in combinations(range(n + m), n):
        mask = np.zeros(n + m, dtype=bool)
        mask[list(indices)] = True

        perm_a = pooled[mask]
        perm_b = pooled[~mask]

        # Calculate the permuted test statistic
        permuted = statistic(perm_a, perm_b)

        # Is the permuted statistic at least as extreme?
        if permuted >= observed:
            hits += 1

        total += 1

    # Proportion of permutations at least as extreme
    p_value = hits / total

    return p_value

Both of these implementations enumerate all possible valid combinations for the permutation test. Even with a correct implementation, exhaustive enumeration scales exponentially and so exhaustive enumeration is effectively out of reach.

Monte Carlo permutation testing

The first major optimization is a change in algorithm. Rather than exactly computing the p value, we can instead estimate it using monte-carlo sampling. The core idea is that we can treat the p value as a biased coin flip, given a random permutation, what is the probability that it is more extreme than the initial statistic?

The main benefit of this is that we can now bound the computation needed based on how precise we want p to be, rather than an exponential number of possible permutations.

From the observed data, $X_j\sim\mathrm{Bernoulli}(p)$, and the number of exceedances follows a binomial distribution. Consequently

$$\hat p=K/M,\qquad \operatorname{Var}(\hat p)=p(1-p)/M.$$

We can then sample random permutations from all possible permutations, and use a monte-carlo simulation to estimate $\hat{p}$. We can quantify its simulation uncertainty using the Wilson score interval. Writing $z=1.96$ for an approximate 95% interval, the formula for $\hat{p}$ and it’s confidence interval are given:

$$\frac{K+z^2/2}{M+z^2}\ \pm\ \frac{z}{M+z^2}\sqrt{\frac{K(M-K)}{M}+\frac{z^2}{4}}.$$

import numpy as np

def monte_carlo_test(a, b, statistic, M=10_000, seed=None):
    a, b = np.asarray(a), np.asarray(b)
    n = len(a)
    rng = np.random.default_rng(seed)

    # Calculate the original test statistic
    observed = statistic(a, b)

    K = 0

    # Sample M random permutations
    for _ in range(M):
        mask = rng.random(n) < 0.5

        perm_a = np.where(mask, b, a)
        perm_b = np.where(mask, a, b)

        # Calculate the permuted test statistic
        permuted = statistic(perm_a, perm_b)

        # Is the permuted statistic at least as extreme?
        if permuted >= observed:
            K += 1

    # Estimate the p-value
    p_hat = K / M

    # Calculate the 95% Wilson score interval
    z = 1.96

    center = (K + z**2 / 2) / (M + z**2)
    margin = z / (M + z**2) * np.sqrt(
        K * (M - K) / M + z**2 / 4
    )

    return p_hat, (center - margin, center + margin)

Optimizing the Implementation

Using a Monte Carlo algorithm replaces exponential enumeration ($2^n$) with $O(MN)$ work, where $n$ is the number of data points and $m$ is the number of monte-carlo iterations. Switching from the exact algorithm to a monte-carlo estimate makes the problem tractable even for large $n$. However, this does not mean that the implementation itself is fast. Especially in python, a naive implementation using a for-loop will be too slow in practice. This section will start with a vanilla python implementation of the paired-permutations test, and demonstrate various optimizations to make monte-carlo permutation testing fast enough for practical use on large datasets.

Note: In the following examples, we are assuming a paired test, with the difference in means as the test statistic. The methods described below are generally applicable, but some of the specific optimizations rely on the structure of the difference of means statistics, and might be implemented different for other test statistics.

Tooling

Before we can optimize the code, we need a way to measure performance. We will use cProfile to record function call counts and timings and SnakeViz to visualize the performance results.

python -m cProfile -o profile.prof benchmark.py
snakeviz profile.prof

Baseline implementation

Below is a basic implementation of a paired permutation test, with a difference of means statistic using python lists and for-loops:

import random
import numpy as np

def vanilla_python(vect1, vect2, m):

    tmp_a = [None for _ in vect1]
    tmp_b = [None for _ in vect2]

    initial_statistic = np.mean(vect1) - np.mean(vect2)
    ns, nf = 0, 0

    for _ in range(m):
        for j in range(len(vect1)):
            swap = random.choice([True, False])

            if swap:
                tmp_b[j] = vect1[j]
                tmp_a[j] = vect2[j]
            else:
                tmp_a[j] = vect1[j]
                tmp_b[j] = vect2[j]

        delta = np.mean(tmp_a) - np.mean(tmp_b)

        if delta >= initial_statistic:
            ns += 1
        else:
            nf += 1

    # Estimate the p-value
    p_hat = ns / m

    # Calculate the 95% Wilson score interval
    z = 1.96

    center = (ns + z**2 / 2) / (m + z**2)
    margin = z / (m + z**2) * np.sqrt(
        ns * nf / m + z**2 / 4
    )

    return p_hat, (center - margin, center + margin)

Vanilla implementation performance

For $n=100,000$ and $m=100$, this implementation takes ~31 seconds as a baseline, with random.choice making up the bulk of the runtime. Let’s see if we can do any better.

Vectorization

The first optimizations that we will look at will be to vectorize the operatings using numpy to take advantage of SIMD. For the numpy optimization, we can can introduce a mask of 0s and 1s to perform the shuffling, as well as use vectorization instead of using an inner for-loop:

def numpy_python(vect1, vect2, m):
    initial_statistic = np.mean(vect1) - np.mean(vect2)
    ns, nf = 0, 0

    n = vect1.shape[0]

    for _ in range(m):
        mask = np.random.rand(n) > 0.5
        a = np.multiply(vect1, mask) + np.multiply(vect2, ~mask)
        b = np.multiply(vect1, ~mask) + np.multiply(vect2, mask)

        delta = np.mean(a) - np.mean(b)

        if delta >= initial_statistic:
            ns += 1
        else:
            nf += 1

    # Estimate the p-value
    p_hat = ns / m

    # Calculate the 95% Wilson score interval
    z = 1.96

    center = (ns + z**2 / 2) / (m + z**2)
    margin = z / (m + z**2) * np.sqrt(
        ns * nf / m + z**2 / 4
    )

    return p_hat, (center - margin, center + margin)

This numpy-optimized version runs in ~0.3 seconds (the percall column). This is a whopping 100x speedup from a relatively minor refactor! But there’s still a lot of gains to be had, let’s keep going.

alt text

Algebraic Optimization

Now that the permutation test is implemented in a vector friendly way with numpy, we get some free vectorization speed up. But we can also perform some algebraic manipulations to reduce the number of floating point operations we need to perform. Since we are using the difference of means, we care about the comparison of $T(A, B) \geq T(A’, B’)$ for some permuted samples $A’, B’$.

Let’s start by looking at the equation for the difference of means:

$$ T(A, B) = \frac{1}{n}\sum{A_i} - \frac{1}{n}\sum{B_i} $$

If we write out the inequality that we care about, we can re-arrange it to remove the $\frac{1}{n}$ constant term:

$$T(A, B) \geq T(A’, B’) $$ $$\frac{1}{n}\sum{A_i} - \frac{1}{n}\sum{B_i} \geq \frac{1}{n}\sum{A’_i} - \frac{1}{n}\sum{B’_i}$$ $$\frac{1}{n}\left(\sum{A_i} - \sum{B_i}\right) \geq \frac{1}{n}\left(\sum{A’_i} - \sum{B’_i}\right)$$ $$\sum{A_i} - \sum{B_i} \geq \sum{A’_i} - \sum{B’_i}$$

From that proof, we can see that we don’t need to care about the mean, only the sum. This allows us to eliminate several floating point operations!

Next, we can start with the difference of sum statistics, and derive a way of pre-computing some results for a major speed-up. For this, we’re going to introduce a masking vector $\sigma$ which will indicate whether the two values are swapped or not (0 is not swapped, 1 is swapped). Let’s rewrite our statistic using $\sigma$:

$$ T(A, B) = \sum{A_i} - \sum{B_i}$$ $$ T(A, B) = \left(A^T ( 1 - \sigma) + B^T \sigma\right) - \left(A^T \sigma + B^T (1 - \sigma)\right) $$

Doing a bit of algebraic manipulation, we can simplify the equation to get:

$$ T(A, B) = (A - B)^T 1 - 2(A - B)^T \sigma $$

This is pretty neat! $A - B$ is a fixed quantity, so we only need to calculate it once up front. On top of that, everything is written vector notation, so we can directly translate it into numpy!

Looking at the previous formulation of the test statistic, we can notice another clever optimization:

$$ T(A, B) = (A - B)^T 1 - 2(A - B)^T \sigma $$

Notice that $(A - B)^T 1$ is the initial statistic, and will be constant across all tests! As such, we don’t actually need to compare the statistic to the initial statistic. On top of that, we don’t actually care about the value of the test statistic, we just care if it exceeds the initial test statistic:

$$T(A, B) \geq T(A’, B’)$$ $$ T(A, B) \geq T(A, B) - 2(A’ - B’)^T \sigma$$ $$ 0 \geq - 2(A’ - B’)^T \sigma$$ $$ (A’ - B’)^T \sigma \geq 0 $$

This means that we only need to calculate $2(A’ - B’)^T$ and check if it is greater than 0!

$$T(A, B)\geq T(A’ , B’) \iff (A’ - B’)^T \sigma \geq 0 $$

We can now precompute the differences once and then count exceedances without constructing either group or even computing the full permuted statistic.

def numpy_efficient(A, B, m):
    delta = A - B
    n = A.shape[0]
    ns, nf = 0, 0

    for _ in range(m):
        mask = np.random.rand(n) > 0.5
        criterion = delta.T @ mask

        if criterion >= 0:
            ns += 1
        else:
            nf += 1

    # Estimate the p-value
    p_hat = ns / m

    # Calculate the 95% Wilson score interval
    z = 1.96

    center = (ns + z**2 / 2) / (m + z**2)
    margin = z / (m + z**2) * np.sqrt(
        ns * nf / m + z**2 / 4
    )

    return p_hat, (center - margin, center + margin)

This implementation runs in ~0.20 seconds, and is a 150x speedup over the original algorithm!

Cython: compile the remaining loop

Cython is a programming language that translates python-like code into C/C++. We can use this to rewrite the permutation testing code in a low-level language, but make it available from a python API. This implementation uses Cython to implement the algorithm in a c-like way, using low-level bit-twiddling to achieve much better performance.

from libc.stdlib cimport rand, srand
from libc.math cimport sqrt

cpdef cython_efficient(double[::1] vect1,
                       double[::1] vect2,
                       int m):

    cdef int n = vect1.shape[0]
    cdef int i, j

    cdef int random_bits
    cdef int successes = 0
    cdef int failures = 0

    cdef double criterion
    cdef double p_hat, center, margin
    cdef double z = 1.96

    # Precompute the paired differences
    for i in range(n):
        vect1[i] = (vect1[i] - vect2[i])

    # Initialize the random number generator
    srand(123)

    # Perform m random permutations
    for j in range(m):
        random_bits = rand()
        criterion = 0.0

        for i in range(n):

            # Extract the least significant bit
            # and accumulate the masked dot product
            criterion += (random_bits & 1) * vect1[i]

            # Shift to the next random bit
            random_bits >>= 1

            # Replenish the random integer
            if random_bits == 0:
                random_bits = rand()

        # Evaluate the comparison criterion
        if criterion >= 0:
            successes += 1
        else:
            failures += 1

    # Estimate the p-value
    p_hat = <double>successes / m

    # Calculate the 95% Wilson score interval
    center = (successes + z**2 / 2) / (m + z**2)
    margin = z / (m + z**2) * sqrt(
        <double>successes * failures / m + z**2 / 4
    )

    return p_hat, (center - margin, center + margin)

Build with setuptools and Cython:

# setup.py
from setuptools import setup, Extension
from Cython.Build import cythonize

setup(
    ext_modules=cythonize([
        Extension(
            "permtest_c",
            ["permtest_c.pyx"],
            extra_compile_args=["-O3", "-mavx", "-ffast-math"]
        )
    ])
)
python setup.py build_ext --inplace

You can then invoke the code by importing the cython module:

from permtest_c import cython_efficient
import numpy as np

n = 100_000
m = 100

# Generate sample data
A = np.random.normal(0, 1, n)
B = np.random.normal(0.1, 1, n)

# Perform the permutation test
p_hat, (lower, upper) = cython_efficient(A.copy(), B.copy(), m)

This Cython implementation completes in a staggering 0.04s, which is a a 750x speedup over the original python code!

Final Results

For N=100,000 and M=100, we can oserve the runtime and speedups for the different implementations of the permutation testing algorithm

Implementation Runtime Relative speedup
Vanilla Python 30 s 1×
NumPy + mask 0.3 s 100×
NumPy + mask + algebra 0.20 s 150×
Cython + compiler flags 0.04 s 750x

Conclusion

Permutation testing is a great example of how a conceptually simple statistical test can present a surprisingly interesting computational challenge. In this article, we saw how Monte Carlo sampling can turn a computationally intractable problem into a tractable one, and how a combination of vectorization, algebraic manipulation, and low-level optimizations can dramatically reduce its runtime.

Additionally, we saw how performance gains can come from more performant code (numpy vectorization and Cython) as well as mathemtical manipulation to simplify the calculations themselves. Together, these techniques make permutation testing a practical and powerful tool, even for large datasets.