Training models
m2n2 whole training pipeline is:
- Initialization of \(\beta\) and the variances.
- minibatches gradient descent on the loss of the network parameters, \(\beta\) and all variances.
- Validation at each epoch, early stopping and restoration of the best state.
- Polish: REML and HMME with the networks frozen.
The fit method
model.fit(
n_epoch = 1000,
batch_size = None,
validation = 0.2,
patience = 50,
verbose = True,
full_REML = True,
lr_beta = 1e-3,
lr_var = 1e-3,
scheduler = None,
)| Argument | Meaning |
|---|---|
n_epoch |
Maximum number of epochs. Defaults to 1000. |
batch_size |
Individuals per minibatch, with all their responses. Defaults to None: full batch. |
validation |
Fraction of the labelled individuals held out for early stopping. Defaults to None: no validation. |
patience |
Epochs without improvement of the validation score before stopping. Defaults to 50, None never stops. |
verbose |
Prints the loss and the score at each epoch. |
full_REML |
Runs the pyreml initialization and the REML of the polish. Defaults to True; False skips both, for datasets too large for them. |
lr_beta |
Learning rate of \(\beta\). Defaults to 1e-3. |
lr_var |
Learning rate of the variances. Defaults to 1e-3. |
scheduler |
Factory of the learning-rate scheduler of \(\beta\) and the variances. Defaults to None: constant learning rates (see Optimizers and schedulers). |
Initialization
Neural weights
m2n2 does not initialize the network weights. The weights can be pre-trained, or re-initialized between runs using the following methods:
model.reset(embedding = "geno", seed = 42)
model.load(embedding = "geno", weights = "pretrained.pt")resetdraws new random weights fromseed, by thereset_parameters()of every submodule that has one: BatchNorm running statistics are reset too, and a parameter held by a module withoutreset_parameters()is left untouched. The global PyTorch generator is not affected.loadloads the weights in place from a file saved bytorch.save(network.state_dict(), "pretrained.pt"). The state dict must match the network, buffers included, e.g. the features \(z\).
Both act in place: the network is not to be replaced in its Embedding, as the RandomNN terms keep a reference to it.
Fixed effects and variances
With
full_REML = True, the model is first fitted by pyreml without theRandomNNterms, on the labelled rows: it initializes \(\beta\), and the variances of theRandomterms and of the residual.With
full_REML = False, this fit is skipped: \(\beta\) is initialized by ordinary least squares on the labelled rows, and the variances of theRandomterms and of the residual at their pyreml initial values.
In both cases, the variances of the RandomNN terms are initialized at the variance of the response; with several responses, \(S_j\) is initialized at the diagonal of their variances, without covariance.
Loss function
Once the random effects are integrated out, the model reads:
\[ y \sim N\big(X\beta,\ V\big), \qquad V = \sum_j Z_j G_j Z_j^\top + R, \]
with one term \(j\) per random effect, and \(R\) the covariance of the residual.
For a
RandomNNterm, \(Z_j = \bigoplus_{k=1}^{q_j} \nu(z_{(k)}, \theta)\), with \(\nu\) the network of itsEmbeddingand \(q_j\) the number of groups, and \(G_j = \sigma^2_{u_j} I\); with several responses, \(G_j = S_j \otimes I_{q_j d}\) (see Several responses).For a pyreml
Randomterm, \(Z_j\) and \(G_j\) follow its specification.The pyreml
Residualterm provides the structure for \(R\).
The network parameters \(\theta\) only enter \(V\): like the variances, they are variance parameters, estimated jointly with \(\beta\) by restricted maximum of likelihood (REML):
\[ -2\ell_{\text{REML}} = \log\lvert V\rvert + r^\top V^{-1} r + \log\lvert X^\top V^{-1} X\rvert + (n - p) \log(2\pi), \qquad r = y - X\beta. \]
The random effects \(u_j\) do not enter the loss: they are predicted afterwards by solving Henderson’s mixed model equations (HMME).
Minibatches
At each epoch, the labelled training individuals are shuffled and split into minibatches of batch_size individuals, the incomplete last batch dropped. An individual enters a minibatch with all its observed responses, which the residual may correlate. As the embeddings are computed row-wise, the covariance of a minibatch \(B\) is the submatrix \(V_B\) of \(V\), and \(y_B \sim N(X_B\beta, V_B)\) exactly: the loss of a minibatch is the REML of the corresponding sub-model. When a level is absent from the minibatch, \(X_B\) loses rank, e.g. an empty column, or the reference level of a qualitative effect, the intercept being then the sum of the present dummies. The REML of the sub-model is then computed on a basis of the columns of \(X_B\), selected by pivoted QR: the fixed effects it cannot estimate are left out of this minibatch. The observations are not independent: they share the \(u_j\), and \(V\) is not diagonal. The minibatch losses therefore do not add up to the full REML: minibatch descent is a stochastic approximation of it, which performs well empirically (Simchoni & Rosset, 2023).
The loss is computed by pyreml, on the SMW path when the total number of columns of \(Z = [Z_1 \mid Z_2 \mid \dots]\) is below \(n_B\), on \(V_B\) directly otherwise. The gradient flows by autograd through the variances, \(\beta\) and the networks. Each network is stepped by the optimizer of its Embedding, AdamW (Loshchilov & Hutter, 2019) by default, and \(\beta\) and the variances by Adam (Kingma & Ba, 2017), at the learning rates lr_beta and lr_var (see Optimizers and schedulers). A network shared by several terms is embedded once per minibatch: its gradient gathers the contributions of all of them, and its optimizer steps once.
model.loss records the mean minibatch loss of each epoch. It scales with \(n_B\): curves are comparable at fixed batch_size only.
Optimizers and schedulers
| Group | Parameters | Optimizer | Weight decay | Learning rate | Scheduler |
|---|---|---|---|---|---|
| Network weights | Tensors of dimension \(\geq 2\) | optimizer of the Embedding |
optimizer |
optimizer |
scheduler of the Embedding |
| Network biases, normalization parameters | Vectors | optimizer of the Embedding |
0 | optimizer |
scheduler of the Embedding |
| Fixed effects | \(\beta\) | Adam | 0 | lr_beta |
scheduler of .fit() |
| Variances | \(\log \sigma^2\), or the parameters of \(S_j\) | Adam | 0 | lr_var |
scheduler of .fit() |
Networks
- Optimizer, required: a
torch.optimoptimizer, LBFGS excepted, as a factory called on the two parameter groups of the network. Defaults topartial(torch.optim.AdamW, lr=1e-3, weight_decay=1e-1). - Scheduler, optional: a
torch.optim.lr_scheduler, as a factory called on the optimizer. Defaults toNone: constant learning rate. - Setting: at the construction of the
Embedding, or afterwards by its name, withmodel.set_optimizer()andmodel.set_scheduler();model.get_optimizer()andmodel.get_scheduler()return them.
model.set_optimizer(
"geno",
partial(
torch.optim.AdamW,
lr = 1e-4,
weight_decay = 1e-1
)
)
model.set_scheduler(
"geno",
partial(
torch.optim.lr_scheduler.CosineAnnealingLR,
T_max = 1000
)
)Fixed effects and variances
- Optimizer: Adam, at the learning rates
lr_betaandlr_varof.fit(). The variances are log-parameterized. - Scheduler, optional: the
schedulerargument of.fit(). It scales both groups together, fromlr_betaandlr_var.
Behavior
- Creation: optimizers and schedulers are created anew at each
.fit(), as \(\beta\) and the variances are initialized anew. The networks keep their weights. - Step: each scheduler steps once per epoch, after the last minibatch. Scheduler lengths, e.g.
T_maxorstep_size, count epochs. ReduceLROnPlateau: steps on the validation score of the epoch, or on its mean minibatch loss withoutvalidation.- Polish: the schedulers do not act on it.
Validation and early stopping
Trained on the marginal likelihood, a deep kernel can overfit more severely than a network trained alone (Ober et al., 2021). For this reason, an early stopping strategy is proposed by m2n2.
With validation set, a fraction of the labelled individuals is held out once, at random, with all their responses. At each epoch, the networks in eval() mode, the held-out rows \(v\) are predicted by their BLUP from the training rows \(t\):
\[ \hat y_v = X_v \beta + Z_v G Z_t^\top V_t^{-1} (y_t - X_t \beta), \qquad V_t = Z_t G Z_t^\top + R_t, \]
with \(Z = [Z_1 \mid Z_2 \mid \dots]\) and \(G\) the block diagonal of the \(G_j\). Their mean squared error is recorded in model.score. With several responses, the score is the mean over the responses of \(\text{MSE}_r / \text{var}(y_r)\), so that no response dominates by its scale.
The best state (weights of every network, \(\beta\), variances) is kept. Training stops after patience epochs without improvement, and the best state is restored. Without validation, training runs n_epoch epochs and the last state is kept.
Each validation solves a dense system in \(V_t\), of size \(n_t \times n_t\).
The held-out rows, the minibatches and the dropout masks all draw from the PyTorch generator: torch.manual_seed makes the training reproducible, the network weights being set beforehand (see Neural weights).
Polish
The networks are frozen in eval() mode and the embeddings computed once. The model is then a linear mixed model with a known random design, refitted by pyreml on every labelled row, held-out ones included:
- REML re-estimates \(\beta\) and the variances, by L-BFGS with its adaptive convergence criterion;
- HMME gives the BLUE of \(\beta\), the BLUP of every \(u_j\), and their error variances.
Both run in double, as the whole mixed model.
With full_REML = False, the REML is skipped: HMME runs on the variances at the end of training.
Monitoring
| Accessor | Content |
|---|---|
model.loss |
Mean minibatch REML loss at each epoch of the last .fit(). |
model.score |
Validation MSE at each epoch of the last .fit(), standardized with several responses, empty without validation. |
model.opti_REML.loss |
REML loss at each iteration of the polish. |
model.convergence |
Whether the polish met the convergence criterion, None with full_REML = False. |
model.opti_REML.duration |
Wall-clock time of the polish, in seconds. |
The opti_REML accessors are not set with full_REML = False.
model.plot() plots the training curves, here on a small example:
The validation MSE rises once the networks overfit; the dashed line marks the restored epoch, from which the polish is run.