Changelog¶
1.0.1 (2026-11-29) — GitHub release (e1893e3)¶
An example-data and documentation release published on GitHub; the library API
is unchanged since 1.0.0.
New features¶
torch_openreml.example_data.load_wheat_marker_100loadswheat_marker_100.csv, a matrix of 100 genotypes by 17,114 markers. The allele scores are coded(AA, AB, BB) = (1, 0, -1), the continuous imputed values are kept alongside them, and every cell lies in[-1, 1]with no missing entries, so the matrix multiplies directly into the VanRaden kernels \(K_1 = ZZ^\top / d\) and \(K_2 = K_1 \odot K_1\) used by the kernel vignette. The data are redistributed under CC BY 4.0, with the attribution and the list of modifications on the Example Datasets page.
Documentation¶
Added eight vignettes covering the matrix and operator interfaces, random intercepts, random slopes, random effects with a known covariance, linear and quadratic kernel models, nonlinear design matrices, and neural-network variance functions.
Reworked
docs/source/vig/vig_factor_analysis.rstaround a balanced and an unbalanced fit of the simulated FA(2) trial, and extended the comparison to the untested-cell BLUPs and the choice of factor count.The Example Datasets page now documents
fa_met,fa_met_paramsandload_wheat_marker_100alongsidejohn_alpha, with their columns, shapes, dtypes, generating values and provenance.
1.0.0 (2026-11-20)¶
This is the first stable release, and it follows 0.4.0-alpha directly. The
jump to 1.0.0 marks that the interface below — MixedModelREML together with
the methods backends — is the shape the package intends to keep: later
releases stay backward compatible with it, and breaking changes are reserved
for a major version.
Breaking changes¶
MarginalREMLhas been removed, andtorch_openreml.marginal_remlno longer exists. Its replacement isMixedModelREML, which takes one or more random-effect(design, covariance)terms and a keywordRfor the residual covariance, builds \(V = R + Z G Z^\top\) withMarginalCovariance, and selects a numerical backend instead of taking a singlevmatrix. Code that passedvtoMarginalREMLmust be rewritten in this form; the post-estimation functions intorch_openreml.postare unchanged.Operator.call_treeis nowOperator.tree. It andOperator.grad_treeeach return a single dict now, rather than a pair of dicts:treemaps a path to the matrix the node evaluated to, andgrad_treeto that node’s(grad, grad_names)pair. The per-node parameter slices they used to return alongside moved tofree_param_tree.
Changes¶
Matrix.set_param_specsdistributes each field it is given: a single value is broadcast to every resolved specification, while a sequence holding one value per specification is split element-wise — aboolor a list or tuple of bools forfixed, aTransformor a list or tuple of transforms fortrans, and a length-1 orlen(specs)tensor fordefault. Any other length raisesValueError, and a value of the wrong type raisesTypeError, before anything is written. Previously every specification was assigned the value as given, so a tensor longer than one parameter was duplicated across specifications instead of split between them.MixedModelREML.optimizenames its starting covariance parametersinit_valuesrather thantheta; positional calls are unaffected, buttheta=must be renamed.updatekeeps itsthetaargument, where the name does mean an estimate.MixedModelREML.optimizeconvertsyandxto the dtype and device of the initial covariance parameters once, then stores the converted tensors for the post-fit methods, instead of repeating the conversion inside every step.MixedModelREML.optimizereplaces the fixedetastep ofMarginalREML.optimizewith Armijo backtracking. The AI direction is unchanged; the step starts ateta_maxand is multiplied byeta_shrinkafter each rejected candidate until the log-likelihood increases sufficiently, with a small gradient-ascent step when no candidate qualifies. This keeps the fit stable when the score or AI matrix is inaccurate.MixedModelREML.optimizeuses a relative Armijo slack (armijo_slack=1e-7) in its sufficient-increase test, so a step within floating-point noise is accepted. Setarmijo_slack=0for strict Armijo.MixedModelREML.historyrecords the backend that produced each AI step under"method", alongsidefree_params,loglik,score,ai,delta,update,etaandaccepted.ai_stepandloglikreturn the method with their numerical result.
New features¶
MixedModelREML, the new frontend for linear mixed models. Each random-effect term is a(design, covariance)pair;R=supplies the residual covariance and defaults to aScalarMatrixwhose dimension is inferred from a random-effect design. Free parameters are ordered as[Z, G, R]and exposed with namespaced names.method=accepts"auto"(the default),"cform","marginal", or a configuredCForm/Marginalinstance;"auto"usesCFormwhen the model is eligible and falls back toMarginalwith a warning if CForm fails.optimizeruns AI-REML with Armijo backtracking, andbuild_params,tree,c_inverse_blocksandget_free_paramsexpose the fitted structure.torch_openreml.methodswith the two public numerical backends:CFormfor dense, invertibleGandRandMarginalfor the generalV-based case, including multiple random-effect blocks and approximate traces. Both expose score, average-information and restricted log-likelihood;Marginaladds thetrace_approxcontrols.MixedModelREMLpost-fit quantities:blue,cov_blue,var_blue,blup,cov_blup,var_blup,blup_per_term,cov_blup_per_term,var_blup_per_term,marginal_predict,marginal_residual,predict,predict_new,residualandloglik. They reuse the response and design stored byoptimizewhenyandxare omitted, and acceptfree_params="last"or"best".predict_newpredicts at new rows from already-built design matrices, withzgiven as a full matrix, a list per term, or a dict keyed by term name.post.cov_blueandpost.var_blue, andpost.cov_blupandpost.var_blup, the sampling covariance and variance of the fixed-effect estimates and random-effect predictions.cov_blueis theC11block of the inverse coefficient matrix andcov_blupuses \(G Z^\top P Z G\), which needs onlyVto be invertible.KnownMatrix, wrapping a fixed two-dimensional tensor as aMatrixwith no free parameters. It follows the parameter tensor’s dtype and device when one is supplied, and precomputes the inverse for a square, invertible matrix.MarginalCovariance, an operator with exactly three named operands,Z,GandR, evaluating \(R + Z G Z^\top\). It validates the design and covariance shapes and namespaces parameters asZ/...,G/...andR/...; it is the operatorMixedModelREMLbuilds.Matrix.manual_inverse, the opt-in closed-form inversion hook. The base implementation raisesNotImplementedError, so a matrix without a closed form fails loudly; concrete implementations exist forScalarMatrix,IdentityMatrix,DiagonalMatrix,EquicorrelationMatrix,AR1Matrix,CompoundSymmetricMatrix,AdapterandKnownMatrix.Operator.operands_manual_inverseis the corresponding operator hook and propagatesNotImplementedErrorwhen an operand has no closed form, with implementations forBlockDiagonal,Product,KroneckerProduct,TransposeandInverse.Matrix.resolve_dim, letting these matrix constructors take a list, tuple orpandas.Seriesof levels instead of an integer dimension; the dimension is the number of distinct levels. It is used byScalarMatrix,IdentityMatrix,DiagonalMatrix,AR1Matrix,CompoundSymmetricMatrix,EquicorrelationMatrix,EqualEntryMatrix,LowerTriangularMatrixandUnconstrainedMatrix.Adapter.manual_inverse, forwarding its mapped parameters to the adaptee’smanual_inverse, so a reparameterised matrix keeps the adaptee’s closed form instead of falling back to a dense inversion.Operator.walk, listing every node of the operand tree as one(path, operand, free_params)triple, in the ordertree,free_param_treeandgrad_treereport. The first entry is always("/", self, free_params): the operator itself and the validated input tensor, whose dtype and device are the resolved ones, while a fixed tensor operand getsNone. The walk validates and splits the parameters and reads the operand structure, so it evaluates nothing — the other three methods are built on it.Operator.free_param_tree, mapping the same paths astreeto the 1D free-parameter slice each node received: the root entry is the validated input tensor and the remaining entries are views of it, while fixed tensor operands getNone. It evaluates no operand, so it is the cheap way to inspect how a composite splits its parameters between operands.MixedModelREML.tree, evaluating the fitted covariance structure at a parameter estimate and returning the same path-keyed dict asOperator.tree, the root"/"holding \(V(\theta)\) itself. It takes afree_paramstensor or dict, or the selectors"last"and"best";tree()uses the last fitted iterate. Whenvis a plain matrix rather than an operator, the tree is the root entry alone.torch_openreml.example_data.fa_met, the simulated FA(2) multi-environment trial used by the factor-analysis vignette, shipped astorch_openreml/example_data/data/fa_met.csvand read into a DataFrame. The genotype and environment labels are read as strings, preserving the zero-padding thatDummyMatrix’s lexicographic ordering relies on, and thegeneticcolumn holds the latent effects that generated the yields.torch_openreml.example_data.fa_met_params, the generating values of that trial (environment means, FA(2) loadings and uniquenesses, residual variance), shipped astorch_openreml/example_data/data/fa_met_params.jsonand read into a dict.DummyMatrix.transform, building the design matrix of new observations from the columns fixed at initialisation: each row is one-hot in the column named by the"⋈"join of its factor values, and a combination with no column — an unseen level, or the reference combination dropped bydrop_first— is an all-zero row. New levels therefore cannot widen the matrix, which makes the result thezblock thatMixedModelREML.predict_newexpects. It takesdtypeanddevicekeywords, defaulting to the PyTorch defaults, and emits no warning, since it cannot tell a dropped reference from an unseen level.
Bug fixes¶
post.blue,post.blupandpost.predictnow keep at least one dimension: they end in.squeeze(-1)instead of.squeeze(), so a single fixed effect, a single random effect or a single observation returns the documented(p,)/(q,)/(n,)shape rather than a 0-d tensor. This also fixes the downstreammarginal_predict,marginal_residualandblupfailures for those cases.MixedModelREML.is_convergednow raisesValueErrorwith an explanatory message when called beforeoptimize(), instead of leaking aTypeErrorfrom aNonehistory.MixedModelREML.optimizekeepsdeltaone-dimensional when the model has one covariance parameter, instead of a 0-d tensor.Operator.build_params(..., out_format="dict")now returns one-element tensors keyed by the names that matchinclude_fixed; previously it returned 0-d scalars and always used the free-parameter names.AR1Matrixcomputes the correlation derivative without dividing by a clampedrho, which previously replaced|rho| < 1e-6and produced a wrong gradient atrho == 0.Marginalnow rejectstrace_approxvalues other thanTrue,Falseor"auto". Previously0and1passed validation and then matched no dispatch branch, ending inUnboundLocalError.CFormcasts a fixed-tensor (or zero-parameterMatrix)Zto the free parameters’ dtype and device, so a float32 design with float64 parameters no longer fails in matmul.EqualEntryMatrix,LowerTriangularMatrixandUnconstrainedMatrixnow validate the size of a customparam_specsat construction.EqualEntryMatrixrequires exactly one spec, so a multi-parameter surface is rejected instead of producing a broadcast(1, n, m)gradient. The two lower-triangular classes require one spec per slot: short custom surfaces previously broadcast silently and then failed insidemanual_gradwith a maskedIndexError, while long ones raisedRuntimeErrorfrom the assignment.
Documentation¶
Updated the API, README, R-user guide and examples for
MixedModelREML, themethodsbackends,manual_inverseand the path-keyedtreeoutput. The API reference gained themethodspage and theKnownMatrix,MarginalCovarianceand post-fit covariance entries; the oldMarginalREMLvignette moved todocs/archive/. The R examples now useMixedModelREMLwithbuild_params(),blue(),blup()andblup_per_term().Added a factor-analysis vignette,
docs/source/vig/vig_factor_analysis.rst, which loads a simulated FA(2) multi-environment trial, fits it withMixedModelREML, and checks the recovery of the covariance, the random effects and the environment means. A second part refits the same model on an unbalanced version of the trial, in which each genotype is grown in only three of the six environments, and compares the recovery, the untested-cell BLUPs and the factor-count choice. The trial is shipped astorch_openreml/example_data/data/fa_met.csvand exposed astorch_openreml.example_data.fa_met, with the latent effects in itsgeneticcolumn; the generating values are shipped asfa_met_params.jsonand exposed astorch_openreml.example_data.fa_met_params.Marginal.ai_stepnow documents theAttributeErrorraised whenmodelisNone; the previous docstring claimedValueError. It also states thatrequire_loglik=Falsereturns thetorch.nansentinel.The
postmodule and API page now document the fixed1e-6 * Iridge added before factorisingV; the behaviour itself is unchanged.
Testing¶
Added
tests/test_mixed_model_reml.py,tests/methods/test_cform.pyandtests/methods/test_marginal.py, with matching planning documents, for the new estimator and both numerical backends.Extended
tests/example_datawith checks on the shippedfa_mettrial andfa_met_params: 1200 observations, two replicates per genotype-by-environment cell, zero-padded string labels, the documented dtypes, ageneticcolumn constant within each cell, and the generating values.Added dedicated tests and plans for
param,post,KnownMatrix,Gram,MarginalCovariance,EqualEntryMatrix,LowerTriangularMatrixandUnconstrainedMatrix.Added dedicated tests and plans for the
Inverse,Product,StackandTransposeoperators, and plans forAdapterandSimpleMatrix. Expanded the matrix and operator tests formanual_inverse,resolve_dim,tree,walk,free_param_treeand the distributedset_param_specsform, and removed the obsoletemap_theta_to_v/map_theta_to_dvtests.Expanded the suite to cover every exported module: each test module now has a matching
test_plan_<module>.md, andtests/test_summary.mdrecords the per-module status. The default pytest path is now the wholeteststree rather than onlytests/covariance.
0.4.0-alpha (2026-10-05)¶
Breaking changes¶
simple_param_specsandSimpleMatrixnow take their default as a 1D tensor of shape(1,). A default passed as a float raises aTypeError, and a tensor of another shape aValueError.Parameter names must be non-empty and must not contain
"/", which the path syntax ofset_param_specsreserves as its separator. Operand names in an operator follow the same rule.
New features¶
New operators:
Product, the matrix product \(V = A B\) of exactly two operands;Transpose, \(V = A^\top\);Stack, binding two or more operands row-wise; andInverse, \(V = A^{-1}\), whose gradient reuses the inverse computed in the forward pass. As with the other operators, each operand may be a trainable matrix or a fixed tensor.Matrix.set_param_specs, updating one or more parameter specifications in place. A key without a trailing"/"addresses one parameter exactly, while a key ending with"/"addresses a subtree:"A/"every parameter of the operand"A", nested operands below it included, and"/"every parameter of the matrix. Each field passed replaces that field of every resolved specification and fields left asNoneare kept, so a call without fields changes nothing. Values are assigned as given, without validation or copying, and take effect on the next call.Matrix.cacheand the cache controlsenable_cache,disable_cacheandreset_intermediates. Disabling the cache also clears it, so an entry stored while caching was on cannot come back when it is turned on again.Operatoroverrides all three to recurse into its matrix operands andAdapterinto its adaptee, so one call covers a whole composite.
Changes¶
MarginalREML.ai_stepnow resolves the dtype and device fromthetaalone and convertsxandyto them, rather than resolving a common dtype and device from the three.
Documentation¶
Added API reference pages for
Product,Transpose,StackandInverse, listed them on the operators page, and regenerated the per-class pages.
Testing¶
Added test modules and planning documents for
Product,Transpose,StackandInverse.
0.3.0-alpha (2026-09-20)¶
Breaking changes¶
IdentityMatrixandDummyMatrixno longer acceptdtypeanddevicearguments. Both follow the dtype and the device of their input instead, falling back to the PyTorch defaults when they receive none.MarginalREML.get_thetaandMarginalREML.get_betano longer accept ahistoryargument, always reading the history populated byoptimize.A composite covariance matrix is now built on a single dtype and device. Where the operands’ own defaults disagree and no input parameters override them, a
ValueErroris raised instead oftorch.catsilently promoting.
New features¶
Operator.call_tree, a debugging view of a composite. It returns two dictionaries over one key set, keyed by the path to each node — the operand names leading to it joined with"/", rooted at"/"— holding the matrix every node evaluated to and the free parameter slice that node received. Nested operators are reached by recursing throughcall_treerather than by capturing the calls a forward pass makes, so the tree is complete whether or not an intermediate cache is warm.Operator.grad_tree, the gradient counterpart over the same keys: each node’s(grad, grad_names)pair, in that node’s own shape, alongside the same parameter slices. A node’s names are namespaced from that node, so joining the path to a name gives the name the composite exposes infree_param_names.Matrix.get_default_dtype_device, reporting the dtype and device that would be resolved from the current parameters.
Changes¶
The dtype and device of a composite are resolved once for the whole structure: the input parameters first, then the free-parameter defaults of the
Matrixoperands, then Torch’s defaults. Input parameters override every default. Fixed tensor operands are never a resolution source — they are cast to follow. The operators and the identity and dummy matrices now observe the resolved dtype and device rather than fixing their own, and the identity and dummy matrices return a clone so a cached result cannot be mutated by the caller.The intermediate cache compares parameter values elementwise rather than hashing them, removing the dependency on
torch.hash_tensorand the limitation it imposed on MPS. A copy of the parameter tensor is stored, so a later in-place edit of the caller’s tensor cannot change the key of an entry already cached.Adapterno longer forces itsparam_specs;param_mapnow receives the free, untransformed parameters.
Bug fixes¶
Fixed silent dtype promotion in the operators, where
torch.catwould promote the results of the operands.Fixed the parameter conversions between dicts and tensors, including the empty case, which now yields an empty tensor rather than failing.
Matrix.auto_gradreturns(None, [])for a matrix without free parameters without building a Jacobian, andtrans_gradreturns an empty tensor where appropriate.The covariance matrices now validate
free_paramsthroughbuild_paramsbefore returning early for a matrix without free parameters, so invalid input raises even there.SimpleMatrixvalidates its input before passing it on.Corrected the documented shapes in
MarginalREML, whose score and AI matrix are sized by the number of free parameters.
Documentation¶
Regenerated and extended the API reference, adding pages for
Adapter,Augment,Gramand the post-estimation functions.Documented the single dtype and device contract on
Operator, and the cost ofcall_treeandgrad_tree.
Testing¶
Added test modules for the adapter and for
Augment, and extended the operator, matrix, identity, dummy and scalar matrix suites to cover the dtype and device contract and the two new tree methods. Device tests follow the accelerator available at run time.Added a test plan document beside each test module under
tests/covariance, recording what must be covered and the risks worth testing.
0.2.0-alpha (2026-09-15)¶
Breaking changes¶
Renamed the
REMLestimator toMarginalREML. The moduletorch_openreml.remlis nowtorch_openreml.marginal_reml, andtorch_openreml.REMLis no longer available.MarginalREMLnow takes a singleMatrixinstance as its only argument. The previous functional interface (v_builder,map_theta_to_v,map_theta_to_gandmap_theta_to_dv) has been removed.Reworked the
Matrixparameter interface. The constructor now takes a singleparam_specsdictionary in place ofparam_names,transandno_grad_index. Each parameter is specified by its own dictionary with the keys"fixed","default"and"trans", so fixed and free parameters can be described together, each with an individual default and transform.Removed
Matrix.from_param_dict,Matrix.to_param_dict,Matrix.map_theta_to_v,Matrix.map_theta_to_dv,Matrix.set_no_gradandMatrix.check_params. Usebuild_paramsand theparam_specsaccessors instead.Matrix.__call__,grad,auto_grad,manual_gradandtrans_gradnow take an optionalfree_paramsargument. When it is omitted, the default value of each free parameter is used, so a matrix can be evaluated without supplying parameters explicitly.Post-estimation methods
marginal_predict,marginal_residualandblupwere removed from the estimator. All post-estimation quantities are now computed by the module-level functions intorch_openreml.post.MarginalREMLkeepsblue,predict,residualandloglikas convenience methods.Removed
utils.categorical_to_design_matrix. Categorical encoding is handled byDummyMatrix.
New features¶
New covariance matrices:
EqualEntryMatrix,UnconstrainedMatrix,LowerTriangularMatrixandSimpleMatrix.New
Adaptermatrix, which reparameterises an existing matrix through a user-supplied mapping from the adapter’s parameters to the adaptee’s parameters, allowing parameters to be combined, split or constrained.New operators:
Gram, computing \(X^\top X\) or \(X X^\top\), andAugment, binding operands column-wise.New
torch_openreml.postmodule with the post-estimation functionsblue,blup,marginal_predict,marginal_residual,predict,residualandloglik, operating directly on tensors.New
simple_param_specshelper for building parameter specifications with a common transform and default.Trace approximation in
MarginalREML.ai_stepandoptimizeaccepttrace_approxandsubspace_fraction, which estimate the trace term of the score from a random subspace instead of computing it exactly.optimizealso acceptsexact_score_threshold, below which the exact score is used again so that convergence is not affected by the approximation.Configurable differentiation.
Matrixexposes agrad_modeattribute ("manual","auto"or"default") and ajacobian_methodattribute, together withjacobian_chunk_size.The package now exposes
__version__.
Changes¶
The default Jacobian method for automatic differentiation is now
"jacfwd", which avoids the memory blow-up that"jacrev"suffers as the matrix dimension grows.identity_matrix,scalar_matrixand the operators were updated to the newparam_specsparameter interface.DummyMatrixgained adrop_empty_colsoption for dropping columns that contain no observations.TransformIdentitynow returns a result of the same length as its input.CompoundSymmetricMatrixandEquicorrelationMatrixnow raise an error forn = 1.
Bug fixes¶
Fixed incorrect gradient computation in
DiagonalMatrix, including the gradient masking and the selection of the manual gradient for all parameters.Fixed
BlockDiagonalwhenfree_paramswas passed as a dictionary.Fixed an empty-tensor concatenation bug in
Matrix.Fixed the gradient and the inverse of
TransformPow.Fixed
Operatorso that nested operators and matrices have their intermediates reset correctly during automatic differentiation.Fixed the operators so that free parameter defaults are used when
free_paramsisNone.
Documentation¶
Added this changelog, a vignette on marginal REML, and a guide for using
torch-openremlfrom R viareticulate.Restructured the API reference, adding pages for the adapter, post-estimation functions and the new matrices and operators.
Rewrote the README with the package overview, features and installation instructions.
Testing¶
Added a pytest suite under
tests/covariancecovering the matrices, the operators, the transforms,utilsand the example data, and registered it as the default test path inpyproject.toml.
0.1.0-alpha (2026-05-08)¶
First release of
torch-openreml