This article trains a small neural network that forecasts the monthly
airline passengers of AirPassengers a year ahead, and
checks the forecast against two years the network never saw. Along the
way you meet zulm’s three objects: a store that holds
parameters, a graph that computes with them, and a
trainer that fits them. Everything runs on the CPU in a
second or two.
The series
AirPassengers counts the passengers of an airline, by
month, from 1949 to 1960. It grows, and its seasonal swing grows with
it, so we work with its logarithm. The first ten years train the
network; 1959 and 1960 are held out to test it.
y <- log(as.numeric(AirPassengers))
n_train <- 120The network reads a year of history and predicts the year after it. Each window is taken relative to its last month, so the network learns changes rather than levels. That lets the trend carry on past the values it was trained on. Within a year the logarithm moves less than 0.6 from a window’s last month, and usually less than 0.3, so multiplying by ten brings the changes near 1, the scale a freshly initialised network works at.
w <- 12 # months of history
h <- 12 # months to forecast
windows <- function(v) {
start <- seq_len(length(v) - w - h + 1)
last <- v[start + w - 1]
list(
x = vapply(start, function(i) v[i:(i + w - 1)], numeric(w)) - rep(last, each = w),
y = vapply(start, function(i) v[i + w + 0:(h - 1)], numeric(h)) - rep(last, each = h)
) |> lapply(function(m) 10 * m)
}
train <- windows(y[1:n_train])
dim(train$x)
#> [1] 12 97train$x has 12 rows and 97 columns: each column is one
example, a window of 12 months, and the same column of
train$y holds the 12 months that follow it. zulm’s tensors
put features first and examples second, the way R stores a matrix column
by column.
Parameters
A store holds a model’s parameters by name. Modules such as
zl_linear() declare their parameters in a store and return
a function that applies them. Declaring the model in a function lets us
build it again later, in another store.
make_model <- function(p) {
hidden <- zl_linear(p, "hidden", n_in = w, n_out = 16)
out <- zl_linear(p, "out", n_in = 16, n_out = h)
function(x) out(zl_silu(hidden(x)))
}
zl_seed(1)
p <- zl_params()
model <- make_model(p)
p
#> <zl_params> 4 tensors, 412 values, 1.6 Kb
#> hidden.weight f32 c(12, 16)
#> hidden.bias f32 c(16)
#> out.weight f32 c(16, 12)
#> out.bias f32 c(12)zl_seed() sets the session’s key. The parameters’
initial values come from it and from their names, so the same seed gives
the same model.
A graph
A graph is built once, from an R function of tensors, for inputs of
fixed dimensions. The function receives the inputs and returns named
outputs; here, a single loss, the mean squared error of the
network’s forecasts.
n <- ncol(train$x)
g <- zl_graph(
function(b) list(loss = zl_mse(model(b$x), b$y)),
p,
inputs = list(x = c(w, n), y = c(h, n)),
loss = "loss"
)
g
#> <zl_graph> 14 nodes; inputs x c(12, 97), y c(12, 97); outputs loss; 19.8 KbNothing has been computed yet. The graph records the operations, and
zl_forward() runs them on data and returns the outputs as a
named list. The loss here is that of the untrained network:
zl_forward(g, train)$loss
#> [1] 4.131582Training
A trainer pairs a graph with an optimiser. Each
zl_step() writes the data into the graph’s inputs, computes
the loss and its gradients, and updates the parameters in the store.
Here every step uses all 97 windows at once.
tr <- zl_trainer(g, zl_adamw(lr = 0.01))
losses <- vapply(1:500, function(i) zl_step(tr, train), numeric(1))
plot(losses, type = "l", log = "y", xlab = "step", ylab = "loss")
Forecasting
To forecast we need the network alone, for one window at a time. A second graph, built on the same store, uses the trained parameters without a loss:
f <- zl_graph(
function(b) list(change = model(b$x)),
p,
inputs = list(x = c(w, 1))
)
forecast_after <- function(end) {
hist <- y[(end - w + 1):end]
change <- zl_forward(f, list(x = matrix(10 * (hist - hist[w]), w, 1)))$change
exp(hist[w] + change / 10)
}We forecast 1959 from the data up to 1958, and 1960 from the data up to 1959. A forecast that repeats the same month of the year before is the baseline to beat.
fc <- c(forecast_after(120), forecast_after(132))
actual <- as.numeric(AirPassengers)[121:144]
naive <- as.numeric(AirPassengers)[109:132]
c(network = mean(abs(fc - actual)), naive = mean(abs(naive - actual)))
#> network naive
#> 20.15044 47.58333The network’s mean error is well under half the baseline’s. The plot shows the held-out years in black and the forecasts in red:
months <- time(AirPassengers)
plot(months[73:144], AirPassengers[73:144], type = "l", xlab = "", ylab = "passengers (thousands)")
lines(months[121:144], fc, col = "red", lwd = 2)
abline(v = months[121], lty = 3)
legend("topleft", c("observed", "forecast"), col = c("black", "red"), lwd = c(1, 2), bty = "n")
A graph is built for its inputs’ dimensions. Giving f
two windows at once is refused before anything runs; to forecast many
windows at a time, build the graph with
inputs = list(x = c(w, k)).
zl_forward(f, list(x = matrix(0, w, 2)))
#> Error:
#> ! Input 'x' has dimensions c(12, 2); the graph was built for c(12, 1).Saving the model
zl_save_safetensors() writes the store’s parameters to a
file. To use them again, declare the same model in a new store and fill
it from the file:
path <- tempfile(fileext = ".safetensors")
zl_save_safetensors(p, path)
p2 <- zl_params()
model2 <- make_model(p2)
zl_load_safetensors(p2, path)
f2 <- zl_graph(function(b) list(change = model2(b$x)), p2, inputs = list(x = c(w, 1)))
x <- matrix(10 * (y[109:120] - y[120]), w, 1)
identical(zl_forward(f2, list(x = x)), zl_forward(f, list(x = x)))
#> [1] TRUEzl_save() writes GGUF files instead, and
zl_load() reads one back as a new store. To stop training
and carry on later, zl_trainer_save() also keeps the
optimiser’s state.
Where next
- Training a model trains a transformer on event sequences with noise drawn inside the graph, shows that training reproduces bit for bit at any thread count, and resumes training from a file.
- Running a pretrained block loads weights exported by PyTorch and decodes through a key-value cache.
- The reference lists every operation and module.