torch-openreml: a PyTorch-based framework for flexible linear mixed-effects modelling

Australasian Applied Statistics Conference · 2026

Weihao (Patrick) Li · Emi Tanaka

Research School of Finance, Actuarial Studies and Statistics, ANU

Why we model the covariance

Multi-environment trial

“Yield across environments is correlated. I want to predict performance in an environment where this genotype was never tested.”

Field experiment

“Plots close together tend to be more alike. If I ignore spatial correlation, my variety comparisons may be less reliable.”

Repeated measures

“The same plot is measured every season. Measurements one season apart are more alike than those five seasons apart. The correlation decays with the time gap.”

Clustered data

“Between-cluster variance is not constant. It changes with cluster-level covariates.”

From predefined structures to custom covariance models

Predefined structures

↑ MORE COVARIANCE STRUCTURES SUPPORTEDlme4(1 | gen) + (1 | rep:block)glmmTMBus(0 + env | gen)ASRemlfa(env, 2):gen

Custom covariance structures are harder to implement

lme4 — no simple user-facing interface for adding new covariance structures. Requires extending its covariance implementation.

glmmTMB — implement a new covariance structure in C++ and modify the R interface. Requires building from source.

ASReml-R — own(): user-defined covariance functions, but requires manually supplying derivative matrices.

Custom covariance models through computation graphs

A factor-analytic model is represented as a computation graph of matrices and operators

θ18 free parameters ΛLowerTriangularMatrixL_i_j loadingsΛΛᵀGram ΨDiagonalMatrixsigma^2_j factorsuniquenessΣSum I₁₀₀IdentityMatrix genotypeenvironmentGKroneckerProduct ZDummyMatrix ZGZ G ZᵀCovariancePropagation RScalarMatrixsigma^2 randomresidualVSum

Custom covariance structures can be built compositionally by combining reusable matrix components and operators in a computation graph.

The same model, written in code

The keyword names are the edge labels, and the free parameters are whatever the matrices declare

Z = DummyMatrix(genotype, environment)

G = KroneckerProduct(
    genotype = IdentityMatrix(genotype),
    environment = Sum(
        factors = Gram(loadings = LowerTriangularMatrix(environment, 2), gram_type = "xxt"),
        uniqueness = DiagonalMatrix(environment)
    )
)

model = MixedModelREML((Z, G), R = ScalarMatrix(len(y)))
model.V.free_param_names
['G/environment/factors/loadings/L_0_0',
 'G/environment/factors/loadings/L_1_0',
 'G/environment/factors/loadings/L_1_1',
 'G/environment/factors/loadings/L_2_0',
 'G/environment/factors/loadings/L_2_1',
 'G/environment/factors/loadings/L_3_0',
 'G/environment/factors/loadings/L_3_1',
 'G/environment/factors/loadings/L_4_0',
 'G/environment/factors/loadings/L_4_1',
 'G/environment/factors/loadings/L_5_0',
 'G/environment/factors/loadings/L_5_1',
 'G/environment/uniqueness/sigma^2_0',
 'G/environment/uniqueness/sigma^2_1',
 'G/environment/uniqueness/sigma^2_2',
 'G/environment/uniqueness/sigma^2_3',
 'G/environment/uniqueness/sigma^2_4',
 'G/environment/uniqueness/sigma^2_5',
 'R/sigma^2']

Average Information REML algorithm

V is the covariance of the observations, \mathrm{Var}(\boldsymbol{y}). In a mixed model V = ZGZ^{\top} + R.
G is the covariance of the random effects, R of the residuals.

the log-likelihood

\ell(\boldsymbol{\theta}) = -\tfrac{1}{2}\Big(\log|V| + \log|X^{\top}V^{-1}X| + \boldsymbol{y}^{\top}P\boldsymbol{y}\Big)

where P = V^{-1} - V^{-1}X(X^{\top}V^{-1}X)^{-1}X^{\top}V^{-1}

which way is uphill

\boldsymbol{s}(\boldsymbol{\theta}) = \tfrac{1}{2}\Big(\boldsymbol{y}^{\top}P\dot{V}_kP\boldsymbol{y} - \operatorname{tr}(P\dot{V}_k)\Big)

how sharply it curves

AI_{kl} = \tfrac{1}{2}\,\boldsymbol{q}_k^{\top}P\boldsymbol{q}_l, \qquad \boldsymbol{q}_k = \dot{V}_kP\boldsymbol{y}

take the step

\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} + \eta\,AI^{-1}\boldsymbol{s}

The estimator needs

V(\boldsymbol{\theta}) the model

\partial V/\partial\theta_k one per parameter

How the graph supplies what the estimator needs

V(\theta)

model.V() evaluates the graph to obtain the marginal covariance matrix.

\partial V/\partial\theta_k

model.V.grad() computes all parameter derivatives, combining analytical gradients with automatic differentiation (torch.func.jacrev) and propagating them through the graph.

V = model.V()
grads, _ = model.V.grad()
print("V        ", V.shape)
print("dV/dtheta", grads.shape)
V         torch.Size([1200, 1200])
dV/dtheta torch.Size([18, 1200, 1200])

Your own matrix, your own operator

A matrix is a function of θ

def compound_symmetry(theta):
    s2, rho = theta[0], torch.sigmoid(theta[1])
    return s2 * ((1 - rho) * torch.eye(6) + rho * torch.ones(6, 6))

V = SimpleMatrix(num_free_params = 2, call = compound_symmetry)

An operator defines how its operands are combined

class Blend(Operator):
    w = 0.5

    def __call__(self, free_params=None):
        a, b = self.build_operands(free_params)
        return self.w * a + (1 - self.w) * b

Custom covariance: a parameter-dependent design

40 subjects, 10 time points each, 400 observations, a decay rate estimated

\begin{aligned} y_{ij} &= \beta_0 + \beta_1 t_j + u_i \exp(-t_j/\tau) + \varepsilon_{ij}, \\ u_i &\sim N(0, \sigma^2_G), \qquad \varepsilon_{ij} \sim N(0, \sigma^2_R) \end{aligned}

\hat\tau = 2.42 (true 2.5) · \hat\sigma^2_G = 0.70 (0.80) · \hat\sigma^2_R = 0.32 (0.30) · BLUP correlation 0.90

-2 0 2 4 6 8 0 2 4 6 8 t y
def decay_design(params):
    tau = params[0].exp()
    return D * torch.exp(-time / tau).unsqueeze(-1)
Z = SimpleMatrix(num_free_params = 1, call = decay_design)
G = ScalarMatrix(n_subject)
model = MixedModelREML((Z, G), R = ScalarMatrix(len(y)))
model.optimize(y, X)

Custom covariance: a learned variance function

2,000 clusters, 3 observations each, a variance function estimated

\begin{aligned} y_{ij} &= \mu_{ij} + u_i + \varepsilon_{ij}, \qquad \mu_{ij} = 2\big(\textstyle\sum_{k} x_{kij} + c_{1i} + c_{2i}\big),\\ u_i &\sim N(0, s_{G,i}^2), \qquad \varepsilon_{ij} \sim N(0, 0.5),\\ s_{G,i} &= 1 + 0.45\,c_1 + 0.35\,c_2 + 0.10\,(c_1^2 + c_2^2) + 0.15\,c_1 c_2 \end{aligned}

Learn the quadratic variance function via a 13-parameter neural network:

G_i = \exp\!\big(\boldsymbol{w}_2^{\top}\operatorname{relu}(W_1\boldsymbol{c}_i + \boldsymbol{b}_1) + b_2\big)

r = 0.996 1 2 3 4 1 2 3 4 True cluster variance Estimated cluster variance

RMSE 0.12 · \hat\sigma^2_R = 0.51 (true 0.50)

def G_cov(theta):
    W1, b1, w2, b2 = theta[0:6].reshape(3, 2), theta[6:9], theta[9:12].reshape(1, 3), theta[12:13]
    v = torch.relu(W1 @ Cc.T + b1[:, None])
    return torch.diag(torch.exp((w2 @ v + b2)[0]))
model = MixedModelREML((Z, SimpleMatrix(13, G_cov)), R=ScalarMatrix(N))
model.optimize(y, X)

Simulation setup and model after Prevett et al. (2026), Gradient Boosted Mixed Models, arXiv:2511.00217.

Custom covariance: a factor-analytic MET

100 genotypes, 6 environments, 2 replicates, 1,200 plots

\begin{aligned} y_{ij} &= \mu_j + u_{ij} + \varepsilon_{ij}, \qquad u_i \sim N(0,\Sigma), \qquad \varepsilon_{ij} \sim N(0,0.3)\\ \Sigma &= \Lambda\Lambda^{\top} + \Psi \end{aligned}

BLUP correlation 0.94 · \hat\sigma^2_R = 0.30 (true 0.30) · \hat\Sigma recovered at r = 0.95

r = 0.936 -3 -2 -1 0 1 2 3 -3 -2 -1 0 1 2 3 True genetic effect BLUP
G = KroneckerProduct(
    genotype=IdentityMatrix(genotype),
    environment=Sum(
        factors=Gram(
            loadings=LowerTriangularMatrix(environment, 2),
            gram_type="xxt"),
        uniqueness=DiagonalMatrix(environment)))
model = MixedModelREML(g_by_e=(Z, G), R=ScalarMatrix(len(y)))
model.optimize(y, X)

01 You define the covariance. torch-openreml provides the estimation framework.

02 Build covariance models compositionally from reusable matrices and operators.

03 Combine analytical derivatives and automatic differentiation to supply the quantities required by AI-REML.

04 Your modelling possibilities are no longer limited to the covariance structures predefined in the library.

Thank you!

installpip install torch-openreml

next R package·formula interfaceboth planned for next year

source github.com/anu-aagi/torch-openreml

website torch-openreml.patrickli.org

slides aasc2026.patrickli.org