Fine-mapping · Python + RustLucaJiang/prusie
On this page

Speed and memory optimization

Fine-mapping large genomic regions or thousands of molecular QTL loci with dense linkage disequilibrium (LD) matrices can be both compute- and memory-intensive. prusie accelerates SuSiE fitting and reduces peak memory usage by caching per-component matrix–vector products, exploiting exact column redundancy in finite-sample LD matrices, factoring invariant terms out of single-effect regression (SER) optimization, and avoiding redundant p×pp \times p matrix allocations.

All optimizations operate in double precision (float64) and preserve the exact statistical model, priors, sequential IBSS update order, and stopping criteria of susieR (see Computational compatibility, Implementation, and Numerical accuracy). Across our empirical benchmarks on 200 FinnGen T2D GWAS loci and 14,157 GTEx whole-blood eQTL genes on exclusive AMD EPYC 7742 nodes, prusie achieved single-threaded runtime speedups of 42.9× in GWAS and 26.6× in eQTL (48.1× and 29.8× in the fitting stage) while reducing median peak memory by approximately fivefold.

Principles

prusie's optimizations reduce arithmetic and memory traffic without altering the statistical problem:

  • No statistical approximations: prusie never thresholds LD entries, prunes variants, or substitutes low-rank approximations. Grouping identical or sign-reversed LD columns accelerates matrix–vector multiplication while maintaining separate posterior probabilities for every variant.
  • Deterministic guards and fallbacks: Specialized execution paths (such as implicit scaling and exact signed-column grouping) check array layout, numerical bounds, and exact floating-point equality before activating, and fall back transparently to general float64 kernels whenever a precondition is not met. Activation of exact-column discovery is governed by deterministic operation counts rather than wall-clock timers.
  • Verified numerical consistency: Because regrouping floating-point additions or multiplications can introduce minor roundoff differences, every optimization is validated against susieR 0.16.6 across the complete L×pL \times p alpha matrix; see Computational compatibility and Numerical accuracy.

Where the time and memory go

For a region with pp variants, LL single-effect components, TT IBSS sweeps, and a candidate credible set of mm variants, the computational complexity and memory footprint of a standard dense Gaussian fit break down as follows:

Stage Time complexity Array storage
Matrix validation and preparation O(p2)\mathcal{O}(p^2) per matrix pass O(p2)\mathcal{O}(p^2) per dense matrix; copies depend on layout and options
Component matrix–vector product O(p2)\mathcal{O}(p^2) per update (ordinary dense kernel) O(p)\mathcal{O}(p) workspace plus O(Lp)\mathcal{O}(Lp) retained component products
Single-effect regression (SER) O(p)\mathcal{O}(p) per posterior and prior-variance objective evaluation O(p)\mathcal{O}(p) scratch plus O(Lp)\mathcal{O}(Lp) posterior arrays
Expected residual sum of squares (ER2) and ELBO O(Lp)\mathcal{O}(Lp) per sweep O(p+L)\mathcal{O}(p + L) scratch (reusing retained products)
Credible-set LD purity O(m2)\mathcal{O}(m^2) pairwise evaluations O(m2)\mathcal{O}(m^2) for sets passing the minimum-correlation check

Over TT sweeps, dense matrix–vector products dominate runtime at O(TLp2)\mathcal{O}(TLp^2) operations, which exact signed-column classes can reduce substantially when perfect-LD redundancy is present. For individual-level data with nn samples, matrix products operate directly on the genotype matrix X\mathbf{X} in O(np)\mathcal{O}(np) time for dense storage or O(nnz+n+p)\mathcal{O}(\mathrm{nnz} + n + p) time for sparse storage using O(n+p)\mathcal{O}(n + p) workspace; see Individual-level designs.

Fewer passes over the input matrix

Reusing the input array

With the default overwrite_ld=False, prusie preserves the caller's input matrix R or XtX. When the input is already an aligned, C-contiguous native float64 NumPy array that is symmetric, the Rust solver borrows its memory directly without copying (treating its transpose as a column-major view of the same buffer). Copies are allocated only when dtype conversion, memory-alignment repair, layout conversion, or symmetry repair is required; see Memory.

Combined validation

A single tiled traversal validates finiteness, nonnegative diagonal entries, and exact symmetry (Qij=Qji\mathbf{Q}_{ij} = \mathbf{Q}_{ji}, checked on (n−1)Rij(n - 1)R_{ij} when n is supplied or raw RijR_{ij} otherwise) without allocating a p×pp \times p transpose temporary (see Shapes and numerical checks).

On x86-64 builds, a fast vectorized pre-check inspects contiguous LD matrices whose diagonal entries lie within 10−810^{-8} of 1 and off-diagonal entries have magnitude at most 1+10−81 + 10^{-8}. If the matrix is proved finite and exactly symmetric (with non-overflowing sample-size scaling), the solver proceeds directly without a second validation pass.

Fused validation and repair

If off-diagonal pairs (i,j)(i, j) and (j,i)(j, i) differ, prusie emits a RuntimeWarning and symmetrizes the working matrix as (Q+QT)/2(\mathbf{Q} + \mathbf{Q}^T)/2. For standard susie_rss fits (overwrite_ld=False, known n, var_y=None, and aligned C-contiguous float64 R), validation and repair are fused into a single pass whenever the fast symmetry proof does not apply: a private buffer is populated during traversal and kept only if an asymmetric pair is encountered (and freed immediately if the matrix turns out to be symmetric). For large matrices (p≥1024p \ge 1024) with n_threads > 1, both the symmetry proof and owned repair can run in parallel across threads; see Threads.

When overwrite_ld=True is opted into, asymmetric entries are instead repaired in place inside the caller's R array without allocating a second p×pp \times p buffer; see Optional LD workspace.

Implicit scaling

Let M\mathbf{M} denote the validated (and, if needed, symmetrized) input matrix and D=diag⁡(d1,…,dp)\mathbf{D} = \operatorname{diag}(d_1, \ldots, d_p) contain the predictor standardization factors. The working Gram matrix is Q=a D−1MD−1\mathbf{Q} = a\,\mathbf{D}^{-1}\mathbf{M}\mathbf{D}^{-1}, where a=n−1a = n - 1 for unrepaired RSS matrices with known nn and a=1a = 1 otherwise. Rather than allocating a separate p×pp \times p matrix to store Q\mathbf{Q}, the solver evaluates matrix–vector products implicitly via two O(p)\mathcal{O}(p) vector scalings:

Qv=a D−1(M(D−1v)). \mathbf{Q}\mathbf{v} = a\,\mathbf{D}^{-1}\bigl(\mathbf{M}(\mathbf{D}^{-1}\mathbf{v})\bigr).

This implicit path is enabled whenever 1≤a≤1091 \le a \le 10^9, all djd_j and 1/dj1/d_j lie in [0.5,2][0.5, 2], and all ∣Mij∣≤2×109|M_{ij}| \le 2 \times 10^9. If any parameter falls outside these bounds (or if an intermediate product produces a nonfinite value), prusie falls back to materializing the scaled matrix Q\mathbf{Q}.

Matrix products in the sweep

Retained component products

Updating component ℓ\ell in IBSS requires the residual crossproduct rℓ=g−∑k≠ℓQmk\mathbf{r}_\ell = \mathbf{g} - \sum_{k \ne \ell} \mathbf{Q}\mathbf{m}_k, where mk=αk⊙μk\mathbf{m}_k = \boldsymbol{\alpha}_k \odot \boldsymbol{\mu}_k is component kk's posterior mean vector. Whereas susieR caches only the total fitted crossproduct f=∑ℓ=1LQmℓ\mathbf{f} = \sum_{\ell=1}^L \mathbf{Q}\mathbf{m}_\ell and recomputes matrix–vector products to remove and restore component contributions and evaluate the ELBO (3L+13L + 1 matrix–vector products per sweep), prusie retains each individual component product uℓ=Qmℓ\mathbf{u}_\ell = \mathbf{Q}\mathbf{m}_\ell alongside their sum f=∑ℓ=1Luℓ\mathbf{f} = \sum_{\ell=1}^L \mathbf{u}_\ell at a cost of only O(Lp)\mathcal{O}(Lp) storage. Updating component ℓ\ell then requires just one matrix–vector product (uℓnew=Qmℓnew\mathbf{u}_\ell^{\mathrm{new}} = \mathbf{Q}\mathbf{m}_\ell^{\mathrm{new}}):

rℓ=g−(f−uℓ),f←f−uℓ+Qmℓnew. \mathbf{r}_\ell = \mathbf{g} - (\mathbf{f} - \mathbf{u}_\ell), \qquad \mathbf{f} \leftarrow \mathbf{f} - \mathbf{u}_\ell + \mathbf{Q}\mathbf{m}_\ell^{\mathrm{new}}.

To illustrate with a two-variant, two-component example:

Q=(2112),g=(10.8),m1=(0.10),m2=(00.2). \mathbf Q=\begin{pmatrix}2&1\\1&2\end{pmatrix},\qquad \mathbf g=\begin{pmatrix}1\\0.8\end{pmatrix},\qquad \mathbf m_1=\begin{pmatrix}0.1\\0\end{pmatrix},\qquad \mathbf m_2=\begin{pmatrix}0\\0.2\end{pmatrix}.

The products are u1=(0.2,0.1)T\mathbf u_1=(0.2, 0.1)^T and u2=(0.2,0.4)T\mathbf u_2=(0.2, 0.4)^T, giving f=(0.4,0.5)T\mathbf f=(0.4, 0.5)^T. Component 1 uses residual (0.8, 0.4). Replacing its mean by m1new=(0.2,0.1)T\mathbf m_1^{\mathrm{new}}=(0.2, 0.1)^T changes the fitted crossproduct to (0.7, 0.8).

The cached products uℓ\mathbf{u}_\ell and f\mathbf{f} are also reused at the end of each sweep to evaluate the expected residual sum of squares (ER2\mathrm{ER2}; see Single-effect posteriors and effect means):

ER2=sy−2gTm+mTf+∑ℓ=1L{∑j=1pQjjαℓjMℓj(2)−mℓTuℓ}. \mathrm{ER2} = s_y - 2\mathbf{g}^T\mathbf{m} + \mathbf{m}^T\mathbf{f} + \sum_{\ell=1}^L \left\{\sum_{j=1}^p Q_{jj}\alpha_{\ell j}M^{(2)}_{\ell j} - \mathbf{m}_\ell^T\mathbf{u}_\ell\right\}.

Because Qm=f\mathbf{Q}\mathbf{m} = \mathbf{f} and Qmℓ=uℓ\mathbf{Q}\mathbf{m}_\ell = \mathbf{u}_\ell are already cached, evaluating ER2\mathrm{ER2} and the ELBO reduces from L+1L + 1 dense O(p2)\mathcal{O}(p^2) matrix–vector products to O(Lp)\mathcal{O}(Lp) dot products (accumulated with compensated float64 summation), cutting the total quadratic work per IBSS sweep from 3L+13L + 1 matrix–vector products to LL.

Dense matrix–vector kernel

prusie's column-major dense matrix–vector kernel skips columns whose multiplier vjv_j is zero and processes nonzero columns in groups of four to minimize load/store traffic on the output vector. On x86-64 processors, runtime feature detection selects an AVX2-accelerated kernel that preserves the exact per-column addition order of the portable scalar kernel. When n_threads > 1, large products partition output rows across threads; see Threads.

Exact signed-column classes

In finite reference panels, sets of variants in perfect positive or negative LD (Rjk=±1R_{jk} = \pm 1) produce identical or sign-reversed columns in the LD matrix. If the pp columns of the multiplied matrix (M\mathbf{M} under implicit scaling, or Q\mathbf{Q} otherwise) partition into gg distinct exact signed-column equivalence classes, prusie sums the signed coefficients within each class (using compensated summation) and multiplies only the gg representative columns, reducing the product cost from O(p2)\mathcal{O}(p^2) to O(pg)\mathcal{O}(pg). When the corresponding row symmetries also hold exactly, a compact g×gg \times g submatrix reduces the cost further to O(g2+p)\mathcal{O}(g^2 + p). Every variant retains its own separate coordinates in alpha, mu, and mu2.

To avoid paying the setup cost of class discovery on fits that converge in just a few sparse updates, activation is controlled by a deterministic work-count rule (activation.rs):

  1. A product is considered dense when at least ⌈p/8⌉\lceil p / 8 \rceil entries of the multiplier vector are nonzero.
  2. On the first dense product, a fast 16-entry column hash estimates a lower bound on the class count gg. If this lower bound already exceeds 7p/87p / 8, discovery is abandoned for the remainder of the fit.
  3. Otherwise, each subsequent dense product accumulates the estimated arithmetic savings of a grouped product over an ordinary product. Once the cumulative projected savings exceed the discovery cost, the solver runs full column verification—confirming every candidate match across all pp rows by exact float64 equality—and caches the grouping plan for all remaining sweeps.

Single-effect regression

During each component update with estimate_prior_variance=True and estimate_prior_method="optim", Brent's method evaluates the SER log marginal likelihood across multiple trial values of the prior variance VℓV_\ell, requiring O(p)\mathcal{O}(p) operations per trial. prusie accelerates this inner optimization loop in four ways:

Grouped sampling variances

In the SER log Bayes factor formula, variants that share the same sampling variance sj2=σ2/Qjjs_j^2 = \sigma^2 / Q_{jj} (floored at float64 machine epsilon ϵ\epsilon) also share the log-determinant term −12log⁡(1+Vℓ/s2)-\frac{1}{2}\log(1 + V_\ell / s^2) and precision factor Vℓ/[s2(Vℓ+s2)]V_\ell / [s^2(V_\ell + s^2)]. Whenever a region has at most 16 distinct sampling variances—and in standard zz-score RSS with a unit-diagonal LD matrix, all informative variants share a single group—prusie evaluates the logarithm and division once per group rather than pp times per trial value of VℓV_\ell:

For s2=0.1s^2=0.1, V=0.2V=0.2 and marginal estimates (0.1,0.2,0.3)(0.1,0.2,0.3), the common log term is -0.549306 and the denominator is 0.03. The log Bayes factors are (-0.515973, -0.415973, -0.249306).

Search invariants

Before launching Brent's search for component ℓ\ell, the solver precomputes the invariant half-squared marginal estimates 12b^ℓj2\frac{1}{2}\widehat{b}_{\ell j}^2 once across all pp variants. When prior weights are uniform (πj=1/p\pi_j = 1/p), the maximum of 12b^ℓj2\frac{1}{2}\widehat{b}_{\ell j}^2 within each sampling-variance group directly identifies the maximum log weight max⁡j(log⁡BFℓj+log⁡πj)\max_j (\log\mathrm{BF}_{\ell j} + \log\pi_j) required for the log-sum-exp shift, eliminating an O(p)\mathcal{O}(p) pass on every Brent evaluation.

Vector exponentials

Evaluating the SER marginal likelihood and normalizing αℓ\boldsymbol{\alpha}_\ell requires exponentiating shifted log weights exp⁡(xj−max⁡kxk)\exp(x_j - \max_k x_k). On GNU/Linux x86-64 builds (unless compiled with portable-math), prusie dispatches these exponentials to glibc libmvec (evaluating four float64 exponentials per AVX2 instruction or two per SSE2 instruction when standard IEEE-754 rounding and subnormal modes are active) and fuses the four-wide log-weight affine transformation.

Summation of likelihood weights

During prior-variance optimization, the nonnegative exponentiated weights exp⁡(xj−max⁡kxk)\exp(x_j - \max_k x_k) are summed using an in-place balanced binary tree so that each term traverses at most ⌈log⁡2p⌉\lceil \log_2 p \rceil additions, while final posterior normalization of αℓ\boldsymbol{\alpha}_\ell and signed dot products in ER2\mathrm{ER2} use compensated float64 summation.

Individual-level designs

For individual-level data (susie), prusie never forms the p×pp \times p matrix XTX\mathbf{X}^T\mathbf{X}. Instead, matrix–vector products are evaluated in two steps as

Qv=XT(Xv), \mathbf{Q}\mathbf{v} = \mathbf{X}^T(\mathbf{X}\mathbf{v}),

incorporating column centering (intercept=True) and standardization (standardize=True) on the fly via precomputed column means and scale factors. Dense genotype matrices cost O(np)\mathcal{O}(np) time per product, compressed sparse column (CSC) matrices cost O(nnz+n+p)\mathcal{O}(\mathrm{nnz} + n + p) time, and 1D trend-filtering designs (susie_trendfilter of order kk) use repeated cumulative sums in O((k+1)n)\mathcal{O}((k + 1)n) time, all using only O(n+p)\mathcal{O}(n + p) working memory alongside the O(Lp)\mathcal{O}(Lp) retained component products. Single-panel susie_rss(..., X=X) also uses this matrix-free design operator except on routes that require an explicit dense covariance matrix (see Supported model and input routes).

Memory

A single dense p×pp \times p float64 matrix requires 8p28p^2 bytes:

At p=5000p=5000, 8p2=200,000,0008p^2=200,000,000 bytes, or approximately 190.7 MiB.

When the caller passes a symmetric, aligned, C-contiguous float64 matrix R (or XtX) and implicit scaling applies, prusie operates directly on the caller's matrix without allocating any additional p×pp \times p arrays—keeping the core solver's working memory at O(Lp)\mathcal{O}(Lp) for alpha, mu, mu2, lbf_variable, and the retained component products uℓ\mathbf{u}_\ell.

Additional p×pp \times p allocations occur only when needed for:

  • coercing non-float64, unaligned, or non-C-contiguous input arrays;
  • fused validation and repair (a temporary buffer is allocated during validation and retained only if the input matrix is asymmetric; in-place overwrite_ld=True avoids this buffer when repairing asymmetric LD);
  • materializing Q\mathbf{Q} when scale factors fall outside the implicit-scaling bounds, or when subsetting columns via maf / appending a physical null column on dense routes (design operators use a virtual zero-cost null column);
  • explicit matrix reconstruction on the bhat/shat/var_y route, dynamic RSS models (R_finite, R_mismatch, multi-panel RSS, susie_rss_lambda), or eigendecomposition when check_input=True;
  • storing a read-only input snapshot when input retention (retain_data=True, track_fit, refine, or warm starts) is requested.

During credible-set purity evaluation on a candidate set of size mm, pairs are checked against min_abs_corr on the fly so that sets failing the threshold short-circuit immediately before allocating the O(m2)\mathcal{O}(m^2) array of pairwise correlations (needed only to compute the mean and median purity of retained sets).

Threads

Because IBSS updates components sequentially—each component depending on the residual left by the preceding component—prusie parallelizes work within each dense matrix–vector product and LD preparation step rather than across components.

When n_threads is set between 2 and 32 (default 1), prusie uses a private per-fit thread pool to partition output rows across workers for dense matrix products with at least 10241024 rows and 102421024^2 entries (using the reduced class count gg when a compact exact signed-column plan is active), while preserving deterministic within-row column summation order. Eligible susie_rss calls (p≥1024p \ge 1024, overwrite_ld=False) also parallelize the symmetry proof and fused validation/repair (see Native threading). Matrix-free design operators and Python dynamic RSS sweeps run serially with respect to n_threads.

Note that n_threads is configured per call (ignoring PRUSIE_NUM_THREADS) and never modifies global BLAS, OpenMP, or Rayon thread pools. In our thread-scaling benchmark across 87 real-data loci, 2 to 4 threads provided consistent speedups (0.799 and 0.735 median runtime ratios relative to 1 thread). When running many fine-mapping analyses in parallel across loci, running single-threaded (n_threads=1) with process-level parallelism across loci typically yields the highest overall throughput.

What prusie does not do

To summarize prusie's design boundaries:

  • No heuristic LD pruning or thresholding: All optimizations preserve full double-precision (float64) SuSiE inference; variant filtering via maf and extended likelihood options occur only when explicitly requested.
  • Numerical rather than bitwise equivalence with R: Because SIMD vectorization, retained-product updates, and grouped column operations reorder floating-point arithmetic relative to R/BLAS, results are validated by numerical agreement on the complete alpha matrix rather than bitwise equality; see Computational compatibility and Numerical accuracy.