Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ jobs:
flake8 . --count --exit-zero --statistics
- name: Check formatting
run: |
black grapp/ setup.py test/ examples/ --check
black grapp/ aireml/ setup.py test/ examples/ --check
- name: Check typing
run: |
mypy grapp --no-namespace-packages --ignore-missing-imports
mypy grapp aireml --no-namespace-packages --ignore-missing-imports
- name: Test with pytest
run: |
PYTHONPATH=$PWD pytest
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ __pycache__/
*.egg-info/
build/
dist/
timing-data/
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,24 @@ stored as a GRG for nearest neighbors in a variety of ways:
* There are APIs that let you query using a sample/mutation already in the dataset (GRG) or more generally
you can query using an external sample/mutation that is not in the dataset, though your options may
be slightly more limited in the latter case.

## aireml (standalone)

The `aireml/` directory is a self-contained package for average-information REML
(AI-REML) estimation of variance components, following
[Lee et al. (2026)](https://doi.org/10.1093/genetics/iyag074). It is deliberately
independent of GRG: it takes a phenotype vector and one or more
`scipy.sparse.linalg.LinearOperator`s standing in for the genetic relatedness
matrix, and never forms an `N x N` matrix. Its only dependencies are `numpy` and
`scipy`, so the directory can be lifted out and used on its own.

```python
from aireml import fit_reml, grm_from_genotypes

grm = grm_from_genotypes(genotypes) # any N x M operator, including a GRG one
result = fit_reml(phenotypes, grm, covariates=covariates)
print(result.heritability, result.heritability_stderr)
```

See [aireml/README.md](https://github.com/aprilweilab/grapp/blob/main/aireml/README.md)
for the algorithm, tuning knobs, and accuracy/runtime checks.
304 changes: 304 additions & 0 deletions aireml/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,304 @@
# aireml

Average-information REML (AI-REML) for variance components whose covariance
structure is only available as a **linear operator**.

This is a small, self-contained implementation of the matrix-free AI-REML
algorithm described in

> Lee H, Pope NS, Kelleher J, Gorjanc G, Ralph PL (2026).
> *Genetic prediction with ARG-powered linear algebra.*
> GENETICS 233(1), iyag074. https://doi.org/10.1093/genetics/iyag074

which in turn builds on Gilmour, Thompson and Cullis (1995).

It depends only on `numpy` and `scipy`, and knows nothing about ARGs, GRGs,
tree sequences, or genotype file formats. You give it a phenotype vector `y`
and one or more `scipy.sparse.linalg.LinearOperator`s, and it estimates the
variance components.

## Why an operator?

For `N` individuals, a genetic relatedness matrix costs `O(N^2)` to store and
`O(N^3)` to factorize, which is hopeless at biobank scale. But every quantity
AI-REML needs can be written in terms of products `B @ x`, and many
representations of relatedness can do that product in nearly linear time: an
ARG/tree sequence (`tskit.TreeSequence.genetic_relatedness_vector`), a GRG, a
sparse or memory-mapped genotype matrix, a low-rank factor, a pedigree.

So `aireml` asks only for the product and supplies the rest:

| need | how |
| ----------------------- | ---------------------------------------------------------- |
| `V^-1 b` | preconditioned conjugate gradients |
| preconditioner | randomized Nystrom (Frangella et al. 2021), sketched once |
| `trace(P V_i)` | XTrace or Hutch++, variance `O(1/m^2)` |
| starting values | randomized Haseman-Elston (Wu and Sankararaman 2018) |
| curvature | average information -- exact, no trace estimate needed |

## Install

```
pip install numpy scipy
```

then either `pip install -e .` from a checkout of this directory's parent, or
simply copy the `aireml/` directory into your project: it is pure Python with
no other dependencies.

## Use

```python
import numpy
from aireml import fit_reml, grm_from_genotypes

genotypes = ... # anything with a matvec: (N, M)
grm = grm_from_genotypes(genotypes) # N x N LinearOperator, Z Z^T / M

result = fit_reml(y, grm, covariates=covariates)
print(result.summary())

result.variance_components # array([tau2, sigma2])
result.heritability # tau2 / (tau2 + sigma2)
result.heritability_stderr # delta method, from the average information
result.fixed_effects # GLS estimate of b
result.blup() # tau2 * B P y, genetic values of the fitted set
```

Bring your own operator -- nothing above is specific to genotypes:

```python
from scipy.sparse.linalg import LinearOperator

relatedness = LinearOperator(
shape=(n, n), matvec=my_relatedness_product, dtype=float
)
result = fit_reml(y, relatedness)
```

Predict genetic values for individuals who were not fitted, given the
cross-covariance block between them and the fitted individuals (Lee et al.
2026, equation 22):

```python
predicted = result.predict(cross_covariance_operator) # (N_new,)
```

Several variance components work the same way; the residual `sigma^2 I` is
always appended automatically:

```python
result = fit_reml(y, [grm_chr1, grm_chr2, grm_chr3])
result.variance_components # array([tau2_1, tau2_2, tau2_3, sigma2])
```

## The algorithm

With `V = sum_i theta_i V_i` and `P` the REML projection matrix,

```
gradient_i = trace(P V_i) - y^T P V_i P y
AI_ij = y^T P V_i P V_j P y
theta <- theta - AI^-1 gradient
```

The average information is the mean of the observed Hessian and the Fisher
information of the REML objective. The expensive trace terms that appear in
each of them cancel in the average, so the curvature is computed *exactly*
from a handful of solves, and only the gradient is stochastic. That is what
makes the optimization stable despite the randomized linear algebra.

Following the paper, iteration stops once the estimates move by less than
`tolerance` (default 5%), runs `extra_iterations` more (default 15), and
returns the average of that window, which averages out the gradient noise.
Set `extra_iterations=0` with `trace_method="exact"` to get a deterministic
fit that converges to machine precision -- that is the mode the tests use to
check the updates against a brute-force maximization of the likelihood.

## Choosing the knobs

| parameter | default | note |
| ---------------------- | --------- | -------------------------------------------------------------------- |
| `num_trace_vectors` | 50 | dominates cost: `2 x this` solves per component per iteration |
| `trace_method` | `xtrace` | or `hutchpp`; `hutchinson` is much noisier. See below |
| `cg_tol` | `1e-5` | relative residual of each solve |
| `preconditioner_rank` | 100 | sketched once per component; raise it when a few eigenvalues dominate |
| `tolerance` | 0.05 | relative change that counts as converged |
| `extra_iterations` | 15 | averaging window after convergence |
| `solver` | `cg` | `dense` materializes `V`; exact, only for small `N` |

## Trace estimators

`trace(P V_i)` is the only quantity in the gradient that cannot be reduced to
a few products, and each product against `P` is a CG solve -- so this choice
drives the runtime. Three unbiased estimators are available, and the fair way
to compare them is at equal *matrix-vector* count, since XTrace spends two
products per test vector while the other two spend one:

| estimator | products | relative SD at 60 products | notes |
| --------- | -------- | -------------------------- | ----- |
| `hutchinson` | `m` | 1.00 | the classical estimator; variance `O(1/m)` |
| `hutchpp` | `3 * (m // 3)` | 0.069 | Hutch++ (Meyer et al. 2021), Algorithm 1 |
| `xtrace` | `2 * m` | 0.053 | Epperly et al. (2024), leave-one-out |

Measured on a 400x400 symmetric matrix with eigenvalues `k^-1.5` over 300
repeats; reproduce with

```
python examples/aireml_benchmark.py --trace-compare
```

Both sketch-and-correct estimators are an order of magnitude better than
plain Hutchinson, and XTrace has a somewhat smaller constant than Hutch++ for
the same number of products, which is why it stays the default. The ordering
is also asserted in `test_variance_ranking_at_equal_matvec_budget`.

One caveat, measured rather than assumed: **this ranking does not carry
through to a better fit.** At N=1500 over 12 seeds at equal product budget
(~25,800 products each), all three estimators converge every time and land on
the same answer:

| estimator | sec | mean h2 | SD h2 | max err |
| --------- | ---:| -------:| -----:| -------:|
| `xtrace` | 14.1 | 0.49602 | 0.00176 | 0.00433 |
| `hutchpp` | 12.9 | 0.49743 | 0.00221 | 0.00380 |
| `hutchinson` | 12.2 | 0.49640 | 0.00168 | 0.00319 |

(exact REML optimum 0.496796). The spreads are within each other's
uncertainty, so even plain Hutchinson is not measurably worse *here*. Two
structural reasons: the average information is computed exactly, so trace
noise perturbs only the search direction and never the curvature; and the
default stopping rule returns the mean of the last 15 iterates, which
averages the remaining noise across iterations.

Runtime is where it gets subtle. XTrace does strictly more dense work per
estimate -- both estimators QR the sketch, but XTrace additionally needs the
triangular solve for `R^-T`, a column normalization, and several m-by-m
products to assemble the leave-one-out terms. Timed in isolation against a
deliberately cheap operator (N=1500, 60 products, 40-60 repeats) that
overhead is plainly visible, and it shrinks as the product gets costlier:

| cost of one product | xtrace | hutchpp | gap |
| ------------------- | -----: | ------: | --: |
| rank-5 update (trivial) | 16.00 ms | 4.97 ms | +222% |
| rank-50 | 8.48 ms | 6.22 ms | +36% |
| rank-200 | 8.95 ms | 9.17 ms | -2% |
| rank-800 | 16.12 ms | 14.89 ms | +8% |

So the overhead matters only when products are cheap. In a real fit each
product is a CG solve, and **the end-to-end difference is not reliably
measurable**: repeated runs put the three estimators within a few percent of
each other in both directions, and a fit that happens to need one extra
iteration spends ~6% more products, which is larger than the effect being
chased. The benchmark reports a `ms/1k mv` column to normalize the iteration
count away, but even that moves by ~5% between runs at the default three
repeats. Do not read an ordering out of a single run.

Two practical consequences, both far bigger than the estimator choice:

* `extra_iterations` dominates the cost/accuracy trade. Dropping it to 0 on
the same problem converges in 2 iterations and 1.5s instead of 17 and 13s,
at a worst-case error of 0.018 rather than 0.004 -- 8x cheaper for 4x the
error. Worth tuning deliberately.
* `num_trace_vectors` matters more than which estimator spends it.

`xtrace` stays the default: lowest variance per product, and the choice in
Lee et al. (2026). Prefer `hutchpp` when products are cheap enough that the
dense overhead shows up, or when you want the simpler estimator.

Hutch++ splits its budget three ways -- sketch, exact trace on the sketched
subspace, Hutchinson correction on the complement -- and is the better choice
if you want a simpler estimator or care about the dense `O(N m^2)` overhead
that XTrace's leave-one-out downdate adds on top of the solves. The
implementation follows the same Algorithm 1 as
`pylops.utils.estimators.trace_hutchpp`, and is cross-checked against it in
the test suite (pylops is not a dependency; the check skips if it is absent).

### Why pylops is not a dependency

`pylops.FunctionOperator` would shorten the operator definitions in
`operators.py`, but it defines only `_matvec`, so the inherited `matmat`
loops over columns one at a time. This package applies operators to blocks of
30-100 columns in trace estimation and in the Nystrom sketch, and measured at
`N = 4000` on a 50-column block that loop costs 8.70 ms against 2.00 ms for an
explicit block `matmat` -- a 4.4x penalty on its hottest operation, and worse
for an ARG or GRG operator where one block product amortizes a graph traversal
across all columns. pylops' operator algebra (`a * Op1 + b * Op2`) degrades
identically. A `pylops.LinearOperator` subclass with an explicit `_matmat`
does preserve blocks, but that is the same custom class this package already
has, so pylops would add no code reduction.

Importing pylops also costs 76 MB of resident memory (42.6 -> 118.5 MB) and
821 ms of startup (350 -> 1171 ms) on top of numpy and scipy, for a package
whose point is to stay light enough to vendor into something else.

## Cost

Per AI-REML iteration, with `m` genetic components and `t` trace vectors:

* `2 t (m + 1)` solves against `V` for the traces,
* `m + 1` solves for the average information,
* `C + 1` solves for the covariates and the phenotype,

each solve being a CG run of a few dozen products against `V`. Nothing is
`O(N^2)`.

## Time trials and memory

`examples/aireml_benchmark.py` runs many fits in one process, which makes it
useless for measuring memory: the high-water mark is whatever the largest fit
needed plus everything the earlier ones left behind. `examples/aireml_timing.py`
does one solve per process so an external profiler sees that solve alone.

```
# write a dataset once per size, then time a single solve
python examples/aireml_timing.py make --dataset data/n16000 --size 16000
/usr/bin/time -l python examples/aireml_timing.py solve --dataset data/n16000

# or drive a whole sweep, which makes any missing datasets itself
python examples/aireml_timing.py trials --sizes 1000 4000 16000 64000
```

`trials` re-runs each solve in a fresh process under the profiler and parses
the peak RSS back out, so the `RSS_MiB` column is a true per-solve high-water
mark rather than a running total. It handles both profiler dialects: GNU time
reports kilobytes under `-v`, BSD/macOS time reports *bytes* under `-l`, which
is an easy way to be wrong by 1024x. On macOS `/usr/bin/time` has no `-v` at
all -- use `-l`, or `brew install gnu-time` for `gtime -v`.

Pass `--grg` to add a `grapp pca` row as a memory baseline on the same data.
That path needs grapp's own dependencies (`pygrgl`, `pandas`); the sweep still
runs without them and says so.

## Accuracy

`test/aireml/` checks, among other things, that

* the analytic gradient matches finite differences of the REML objective,
* the average information matches the explicit `y^T P V_i P V_j P y`,
* AI-REML with exact traces reaches the same optimum as a brute-force
Nelder-Mead maximization of the restricted likelihood (to `1e-5` relative),
* the matrix-free stochastic path lands within a few percent of that optimum,
* the estimates are unbiased across simulation replicates, and the reported
standard errors track their empirical spread,
* BLUPs match the closed-form `tau^2 B[new, fitted] P y`.

`examples/aireml_benchmark.py` measures runtime scaling and compares AI-REML
against Haseman-Elston.

## References

* Gilmour AR, Thompson R, Cullis BR (1995). Average information REML.
*Biometrics* 51(4):1440-1450.
* Lee H, Pope NS, Kelleher J, Gorjanc G, Ralph PL (2026). Genetic prediction
with ARG-powered linear algebra. *GENETICS* 233(1):iyag074.
* Epperly E, Tropp JA, Webber RJ (2024). XTrace: making the most of every
sample in stochastic trace estimation. *SIMAX* 45(1):1-23.
* Meyer RA, Musco C, Musco C, Woodruff DP (2021). Hutch++: optimal stochastic
trace estimation. *SOSA* 2021:142-155.
* Frangella Z, Tropp JA, Udell M (2021). Randomized Nystrom preconditioning.
*SIMAX* 44(2):718-752.
* Wu Y, Sankararaman S (2018). A scalable estimator of SNP heritability for
biobank-scale data. *Bioinformatics* 34(13):i187-i194.
* Patterson HD, Thompson R (1971). Recovery of inter-block information when
block sizes are unequal. *Biometrika* 58(3):545-554.
Loading