torch-openreml
A PyTorch-based library for AI-REML estimation of linear mixed models.
Overview¶
torch-openreml fits linear mixed-effects models using the Average Information REML (AI-REML) algorithm on a PyTorch backend. It supports flexible specification of covariance structures through a modular system of matrices and operators, along with automatic or manual gradients and optional parameter transformations for constrained estimation.
Unlike traditional mixed-model software, it does not provide a formula interface. Instead, users define the fixed- and random-effects design matrices and covariance structures directly in code. The library is focused purely on the computational and optimization backend rather than model specification syntax.
Features¶
Torch-based backend:
Built on PyTorch, supporting execution on CPU, GPU, and other available accelerators.
AI-REML estimation engine
Variance component estimation using average information restricted maximum likelihood (AI-REML), with a Newton-type scoring method, Armijo backtracking, and a gradient fallback.
Extensible covariance structure
Composable covariance structures and operators from built-in and user-defined components.
Hybrid differentiation support
Support automatic differentiation and manually specified gradients.
Composable parameter transformations
Configurable, chainable transformation pipelines for flexible parameterization.
Installation¶
pip install torch-openreml
Dependencies: torch, pandas, tqdm (Python 3.12).
Getting Started¶
Dataset¶
To illustrate a quick start with the library, we begin by fitting a mixed-effects model using
the john_alpha dataset. This dataset contains field trial data from a resolvable alpha lattice design
conducted at Craibstone near Aberdeen.
It consists of 72 observations and 7 variables. In this example, we use yield (dry matter yield) as the
response variable, and rep (replicate identifier), block (incomplete block within replicate),
and gen (genotype or variety identifier) as covariates.
plot rep block gen yield row col
0 1 R1 B1 G11 4.1172 1 1
1 2 R1 B1 G04 4.4461 2 1
2 3 R1 B1 G05 5.8757 3 1
3 4 R1 B1 G22 4.5784 4 1
4 5 R1 B2 G21 4.6540 5 1
.. ... .. ... ... ... ... ...
67 68 R3 B5 G24 3.5655 68 1
68 69 R3 B6 G03 2.8873 69 1
69 70 R3 B6 G05 4.1972 70 1
70 71 R3 B6 G20 3.7349 71 1
71 72 R3 B6 G07 3.6096 72 1
[72 rows x 7 columns]
Model Specification¶
The model includes an intercept, a single categorical fixed effect (rep), a random intercept for gen, and a random interaction effect between rep and block.
The model is specified as:
with marginal covariance structure:
and distributional assumptions:
A design may be a fixed tensor, as in the present model, or a parameterised Matrix whose free parameters are part of \(\boldsymbol{\theta}\).
For the present model, which includes two random intercept components and their interaction, the covariance contribution from the random effects is expressed as:
where \(\mathbf{G}_{rep} = \mathbf{I}\) is fixed as the identity matrix for identifiability.
Import modules¶
We begin by importing the required modules.
import torch
import pandas as pd
from torch_openreml import MixedModelREML
from torch_openreml.covariance import DummyMatrix, IdentityMatrix, ScalarMatrix, KroneckerProduct, Augment
from torch_openreml.example_data import john_alpha
Covariance Builder¶
Next, we construct \(\mathbf{y}\), \(\mathbf{X}\), and the components required to define \(\mathbf{V}\). Both \(\mathbf{y}\) and \(\mathbf{X}\) are represented as torch tensors. The DummyMatrix class serves as a matrix builder: it constructs the dummy matrix upon evaluation and accepts either pandas.Series or lists of strings as input. The argument drop_first=True removes the first column of the dummy matrix to avoid redundancy, as an intercept term is already included.
The classes ScalarMatrix and IdentityMatrix are also matrix builders, parameterized by the required matrix dimension. The dimension may be given as an integer, or directly as the grouping factor itself, in which case the number of distinct values defines the dimension.
Each random-effect term is specified directly as a (design, covariance) pair. The first term is named genotype, with design DummyMatrix and covariance ScalarMatrix. The second is named replicate_block and models the replicate-by-block interaction, whose covariance uses KroneckerProduct for \(\mathbf{G}_{rep} \otimes \mathbf{G}_{block}\). The residual covariance \(\mathbf{R}\) is supplied separately.
MixedModelREML combines the terms into the marginal covariance internally:
with \(\mathbf{G}_{rep} = \mathbf{I}\), \(\mathbf{G}_{gen} = \sigma^2_{gen}\mathbf{I}\), \(\mathbf{G}_{block} = \sigma^2_{block}\mathbf{I}\), and \(\mathbf{R} = \sigma^2_{\varepsilon}\mathbf{I}\).
The model parameters are defined as:
The logarithmic parameterization ensures that the variance components remain positive during optimization.
rep = john_alpha["rep"]
block = john_alpha["block"]
gen = john_alpha["gen"]
n = len(john_alpha)
y = torch.tensor(john_alpha["yield"].values)
X = Augment(torch.ones(n, 1), DummyMatrix(rep, drop_first=True))()
MixedModelREML Optimizer¶
Once the random-effect terms have been specified, they are passed to MixedModelREML as (design, covariance) pairs, and the residual covariance is supplied with the keyword R =:
reml = MixedModelREML(
genotype = (DummyMatrix(gen), ScalarMatrix(gen)),
replicate_block = (DummyMatrix(rep, block), KroneckerProduct(
G_rep = IdentityMatrix(rep),
G_block = ScalarMatrix(block),
)),
R = ScalarMatrix(n)
)
Printing the model shows the marginal covariance it assembles from those terms:
print(reml)
MarginalCovariance(
operands={
'Z': Augment(
operands={
'genotype': DummyMatrix(shape=(72, 24)),
'replicate_block': DummyMatrix(shape=(72, 18))
}
),
'G': BlockDiagonal(
operands={
'genotype': ScalarMatrix(shape=(24, 24), param_specs={'sigma^2': {'fixed': False, 'default': tensor([0.]), 'trans': TransformExpPow2()}}),
'replicate_block': KroneckerProduct(
operands={
'G_rep': IdentityMatrix(shape=(3, 3)),
'G_block': ScalarMatrix(shape=(6, 6), param_specs={'sigma^2': {'fixed': False, 'default': tensor([0.]), 'trans': TransformExpPow2()}})
}
)
}
),
'R': ScalarMatrix(shape=(72, 72), param_specs={'sigma^2': {'fixed': False, 'default': tensor([0.]), 'trans': TransformExpPow2()}})
}
)
The optimize method is then called with \(\mathbf{y}\), \(\mathbf{X}\), and an initial value for \(\boldsymbol{\theta}\) (set to zeros in this example). The verbose argument controls the level of diagnostic output. The response and design are stored on the model, so the post-estimation methods below can be called without repeating them.
Because the optimization is performed on the transformed parameter scale, the estimated parameters can be mapped back to variance components using build_params. The resulting values correspond to the variance components associated with the parameter names stored in free_param_names.
free_param_names, free_params = reml.optimize(y, X, torch.zeros(3), verbose=1)
print(free_param_names)
print(free_params)
print(reml.build_params(free_params))
[ 1] ∥∇∥: 41.8198, ∥Δ∥: 8.9438, η: 0.25, ∥Δᶜ∥: 2.2359, accepted: True , log 𝓛: 13.4244
[ 2] ∥∇∥: 19.0068, ∥Δ∥: 0.4705, η: 1.00, ∥Δᶜ∥: 0.4705, accepted: True , log 𝓛: 16.6687
[ 3] ∥∇∥: 3.6187, ∥Δ∥: 0.0932, η: 1.00, ∥Δᶜ∥: 0.0932, accepted: True , log 𝓛: 16.7988
[ 4] ∥∇∥: 0.1519, ∥Δ∥: 0.0042, η: 1.00, ∥Δᶜ∥: 0.0042, accepted: True , log 𝓛: 16.8141
[ 5] ∥∇∥: 0.0020, ∥Δ∥: 0.0001, η: 0.00, ∥Δᶜ∥: 0.0000, accepted: False, log 𝓛: 16.8081
[ 6] ∥∇∥: 0.0019, ∥Δ∥: 0.0001, η: 1.00, ∥Δᶜ∥: 0.0001, accepted: True , log 𝓛: 16.8137
[ 7] ∥∇∥: 0.0001, ∥Δ∥: 0.0000, η: 1.00, ∥Δᶜ∥: 0.0000, accepted: True , log 𝓛: 16.8157
[ 8] ∥∇∥: 0.0001, ∥Δ∥: 0.0000, η: 0.02, ∥Δᶜ∥: 0.0000, accepted: True , log 𝓛: 16.8157
[∇: score, Δ: 𝐉⁻¹∇, η: step length, Δᶜ: clip(𝛉 + ηΔ, lb, ub) - 𝛉, 𝓛: restricted likelihood]
✓ Converged at iteration 8, total time: 0.03s
['G/genotype/sigma^2', 'G/replicate_block/G_block/sigma^2', 'R/sigma^2']
tensor([-0.9728, -1.3281, -1.2529])
tensor([0.1429, 0.0702, 0.0816])
BLUE¶
With the variance components estimated, the fixed effects follow from generalized least squares, the best linear unbiased estimate (BLUE):
The blue method uses the stored \(\mathbf{y}\) and \(\mathbf{X}\) together with the fitted parameter vector, and evaluates \(\mathbf{V}\) at those parameters internally:
beta_hat = reml.blue()
print(beta_hat)
tensor([ 4.5183, 0.2978, -0.4140])
BLUP¶
Once the variance components have been estimated, the random effects can be predicted using the best linear unbiased predictor (BLUP):
Here, \(\mathbf{Z}\) and \(\mathbf{G}\) are assembled internally from the per-term design and covariance blocks. The blup method returns a prediction for each random-effect level. In this example, the predictions correspond to the 24 genotypes followed by the 18 replicate-by-block combinations:
b_hat = reml.blup()
b_hat
tensor([ 0.5012, 0.0050, -0.7846, 0.0061, 0.4749, 0.0446, -0.3089, 0.0622,
-0.8099, -0.0894, -0.1964, 0.2258, 0.2317, 0.2434, 0.4247, 0.2010,
0.0781, -0.1102, 0.2896, -0.3390, 0.2561, 0.0241, -0.1770, -0.2531,
0.1231, -0.1412, -0.1504, -0.1068, 0.0737, 0.2015, -0.5326, -0.3012,
0.2432, 0.1349, 0.2753, 0.1804, 0.0506, -0.0478, 0.1511, 0.0538,
-0.0080, -0.1996])
blup_per_term splits the same predictions by random-effect term, returning a dict keyed by the term names supplied to the constructor. The random intercepts for genotype are then:
gen_blup = reml.blup_per_term()
print(gen_blup["genotype"])
tensor([ 0.5012, 0.0050, -0.7846, 0.0061, 0.4749, 0.0446, -0.3089, 0.0622,
-0.8099, -0.0894, -0.1964, 0.2258, 0.2317, 0.2434, 0.4247, 0.2010,
0.0781, -0.1102, 0.2896, -0.3390, 0.2561, 0.0241, -0.1770, -0.2531])
Documentation¶
Section |
Description |
|---|---|
Vignettes |
|
Model formulation, REML and ML theory, score and AI matrix derivations. |
|
Full documentation for the REML estimators, covariance matrices, operators, transforms, and utilities. |
Citing¶
@software{torch_openreml,
author = {Weihao Li},
title = {torch-openreml},
year = {2026},
url = {https://github.com/anu-aagi/torch-openreml/}
}