zl_trainer_save() writes a trainer's parameters and its optimiser's
state to one GGUF file: the parameters as zl_save() writes them, in
f32; AdamW's moments of each trained parameter, as f32 tensors named
zulm.opt.m.<name> and zulm.opt.v.<name>; and, as metadata, the step
counts, the optimiser and its settings, and accumulate.
Arguments
- tr
A trainer from
zl_trainer().- path
The file to write or read.
Value
zl_trainer_save() returns path invisibly; zl_trainer_load()
and zl_reset() the trainer, invisibly.
Details
zl_trainer_load() restores such a file into a trainer built like the
one that saved it: the same parameter names and dimensions, the same
optimiser and the same accumulate. It writes the parameters into the
trainer's store, so every graph on that store sees them. Training
resumed this way equals training that was never interrupted, bit for
bit, at the same number of threads or any other, as long as the batches
and the session's zl_seed() are the same. Hyperparameters may differ:
the trainer's own are used.
A trainer can be saved or loaded only between updates: with
accumulate = 4, after a multiple of four steps. The gradients summed
within an accumulation period are not saved. A file whose parameters,
optimiser or accumulate differ from the trainer's is refused, and the
trainer is left as it was.
zl_reset() zeroes the optimiser's state (AdamW's moments and step
count) and the step count that keys in-graph random draws.
zl_load() reads the parameters of a trainer-state file without the
moments.
Examples
new_trainer <- function() {
p <- zl_params()
zl_param(p, "w", c(3, 1), init = zl_init_zeros())
g <- zl_graph(
function(x) list(loss = zl_mse(zl_crossprod(zl_param_tensor(p, "w"), x$x), x$y)),
p,
inputs = list(x = c(3, 8), y = c(1, 8)),
loss = "loss"
)
zl_trainer(g, zl_adamw(lr = 0.05))
}
set.seed(1)
x <- matrix(rnorm(24), 3, 8)
y <- matrix(c(1, -2, 0.5) %*% x, 1, 8)
tr <- new_trainer()
for (i in 1:20) zl_step(tr, list(x = x, y = y))
path <- tempfile(fileext = ".gguf")
zl_trainer_save(tr, path)
tr2 <- zl_trainer_load(new_trainer(), path)
identical(zl_step(tr2, list(x = x, y = y)), zl_step(tr, list(x = x, y = y)))
#> [1] TRUE
unlink(path)