Package 'zulm'

Title: Tensor Graphs, Training and Inference on 'ggml'
Description: Builds computation graphs of tensors in R, runs them on the central processing unit (CPU), differentiates them and trains their parameters, through the 'ggml' tensor library (<https://github.com/ggml-org/ggml>) bundled in its CPU subset. Graphs are built once per input shape and run many times; the same operations train small and medium neural networks with the AdamW (Loshchilov and Hutter (2019) <doi:10.48550/arXiv.1711.05101>) and stochastic gradient descent (SGD) optimisers, and run pretrained transformer checkpoints read from safetensors files or from GGUF files, the model file format of 'ggml'. Results reproduce bit for bit at a fixed seed whatever the thread count. A versioned C interface lets other packages build models on top.
Authors: Pedro Baltazar [aut, cre, cph], The ggml authors [cph] (Bundled 'ggml' library; see inst/COPYRIGHTS), Mozilla Foundation [cph] ('llamafile' matrix kernels in the bundled 'ggml'; see inst/COPYRIGHTS), Jeffrey Quesnelle [cph] ('YaRN' rotary scaling in the bundled 'ggml'; see inst/COPYRIGHTS), Bowen Peng [cph] ('YaRN' rotary scaling in the bundled 'ggml'; see inst/COPYRIGHTS), The Apache Software Foundation [cph] (Arrow C data interface definitions; see inst/COPYRIGHTS)
Maintainer: Pedro Baltazar <[email protected]>
License: MIT + file LICENSE
Version: 0.1.0
Built: 2026-12-06 01:53:57 UTC
Source: https://github.com/pedrobtz/zulm

Help Index


Optimisers

Description

zl_adamw() is AdamW, zl_sgd() stochastic gradient descent, both as 'ggml-opt' implements them. Weight decay is decoupled from the gradient: each step multiplies the parameters by 1 - lr * weight_decay.

Usage

zl_adamw(lr = 0.001, beta1 = 0.9, beta2 = 0.999, eps = 1e-08, weight_decay = 0)

zl_sgd(lr = 0.01, weight_decay = 0)

Arguments

lr

The learning rate, positive.

beta1, beta2

AdamW's moment decay rates, in ⁠[0, 1 - 2^-24]⁠: below 1 once rounded to f32.

eps

AdamW's denominator offset, non-negative.

weight_decay

In ⁠[0, 1]⁠.

Value

An object of class zl_optimizer.

Examples

zl_adamw(lr = 3e-4, weight_decay = 0.01)
zl_sgd(lr = 0.1)

Batches from Arrow streams

Description

zl_arrow_batches() reads record batches from an Arrow stream, such as a 'DuckDB' query, a Parquet file or an 'arrow' table, and cuts them into batches of exactly rows rows for zl_step() and zl_forward(), which take the iterator as data. zl_next() returns the next batch as R arrays, for inspection. Each batch is one copy of the data: columns are interleaved into feature-major arrays, c(features, rows).

Usage

zl_arrow_batches(
  stream,
  map,
  rows,
  na = c("error", "mask"),
  last = c("drop", "pad")
)

zl_next(it)

## S3 method for class 'zl_arrow_batches'
print(x, ...)

Arguments

stream

An Arrow stream: a nanoarrow_array_stream, or an object that 'nanoarrow' converts to one (a data frame, an 'arrow' table or reader).

map

A named list from input names to column names, as above.

rows

The rows per batch.

na

What a missing value does: "error" or "mask".

last

What the final, partial batch does: "drop" or "pad".

it

An iterator from zl_arrow_batches().

x

An iterator, for print().

...

Unused.

Details

map names the graph's inputs and gives each its columns: a character vector for an f32 input of c(length(columns), rows), or zl_int(...) around the column names for an i32 input (a vector of rows for one column). float32 columns are copied, float64 rounded to f32, int8 to int64 and boolean (0 and 1) go to either kind of input, and dictionary-encoded columns of strings go to i32 inputs as their codes, counting from 0. int64 values beyond the 32-bit range are errors in an i32 input. The dictionary must be the same in every record batch. Other types are refused.

Missing values are errors naming the column and row (na = "error"). With na = "mask" they are written as 0, and every input x gets a companion input x_mask of its shape holding 1 for a value and 0 for a missing one. The rows left at the end of the stream are dropped (last = "drop"), or padded with zeros to a full batch (last = "pad"), in which case every batch carries a row_mask input of rows values, 1 for a real row and 0 for padding. A graph that takes the iterator declares these inputs too.

The stream is taken over by the iterator: it is read on the main thread only, as producers such as 'DuckDB' require, and released when it ends or when the iterator is garbage collected. zl_step() and zl_forward() return NULL once it has ended.

A nanoarrow_array_stream is used directly; anything else is converted with nanoarrow::as_nanoarrow_array_stream(), which needs the 'nanoarrow' package (a zulm_companion_error without it).

Value

zl_arrow_batches() returns an iterator of class zl_arrow_batches; zl_next() a named list of arrays, or NULL at the end of the stream.

Examples

if (requireNamespace("nanoarrow", quietly = TRUE)) {
  df <- data.frame(a = c(1, 2, 3, 4, 5), b = c(0.5, 1, 1.5, 2, 2.5),
                   kind = factor(c("x", "y", "x", "x", "y")))
  it <- zl_arrow_batches(df, list(x = c("a", "b"), kind = zl_int("kind")), rows = 2)
  zl_next(it)
  zl_next(it)
  zl_next(it)
}

Convert a tensor's type

Description

zl_cast() converts to "f32", "f16" or "bf16". Operations take f32 tensors, so a half-precision parameter is cast to f32 before any operation but zl_crossprod() and zl_get_rows(). It has no gradient.

Usage

zl_cast(x, type)

Arguments

x

A tensor.

type

The new type.

Value

A tensor.

Examples

p <- zl_params()
zl_param(p, "h", 4, type = "f16", init = zl_init_ones())
g <- zl_graph(function(x) zl_cast(zl_param_tensor(p, "h"), "f32") + x$a,
              p, inputs = list(a = 4))
zl_forward(g, list(a = 1:4))$output

Flash attention

Description

zl_flash_attention() computes softmax(scale * t(k) %*% q + mask) weighted sums of v for every query, head and batch, in one fused operation that holds no matrix of scores, so long contexts attend in memory linear in their length. It is 'ggml”s ggml_flash_attn_ext.

Usage

zl_flash_attention(q, k, v, mask = NULL, scale = 1)

Arguments

q, k, v

Tensors.

mask

NULL, or a tensor added to the scores.

scale

The factor applied to the scores before the mask, usually 1 / sqrt(d).

Details

The layouts are 'ggml”s: q is c(d, n, heads, batch), k is c(d, n_kv, heads_kv, batch) and v is c(d_v, n_kv, heads_kv, batch), not transposed; heads_kv must divide heads. The result is c(d_v, heads, n, batch), heads before positions, so that zl_reshape(o, c(d_v * heads, n, batch)) joins the heads. Trailing dimensions of 1 may be left out of the inputs; the result has at least three.

The mask is added to the scaled scores. It is c(n_kv, n), optionally with third and fourth dimensions that divide heads and batch. The kernel reads it in half precision: 0 and -Inf are exact, other values are rounded to about three significant digits.

The operation has no gradient, so a graph that trains through it is refused; zl_softmax() and zl_crossprod() give the same attention with gradients. Results agree with that plain form to within f32 rounding, and do not depend on zl_threads(): a single query, which 'ggml' would split across threads by key, is computed as two identical queries so that each stays on one thread.

Value

A tensor.

Examples

p <- zl_params()
g <- zl_graph(
  function(x) zl_flash_attention(x$q, x$k, x$v, scale = 1 / 2),
  p,
  inputs = list(q = c(4, 3, 2), k = c(4, 5, 2), v = c(4, 5, 2))
)
dim(zl_forward(g, list(
  q = array(1, c(4, 3, 2)), k = array(1, c(4, 5, 2)), v = array(1, c(4, 5, 2))
))$output)

Build and run graphs

Description

zl_graph() calls build(x) once, with x a named list of input tensors of the declared shapes, and records the tensors build() returns as the graph's outputs. Inside build(), inputs, parameters (from zl_param_tensor()) and the results of operations such as zl_crossprod() are tensors; build() is not called again, and a different input shape needs another graph.

Usage

zl_graph(build, p, inputs, loss = NULL, outputs = NULL)

zl_int(...)

zl_forward(g, data, outputs = NULL)

zl_graph_info(g)

Arguments

build

A function of one argument, the named list of inputs, returning a tensor or a named list of tensors.

p

The parameter store whose parameters build() uses.

inputs

A named list of input dimensions: numeric vectors of one to four positive whole numbers, or zl_int(...) for an integer input.

loss

The name of a scalar output to train on (see the training functions); NULL for none.

outputs

The names of the outputs to keep, of those build() returns; NULL for all.

...

Dimensions, for zl_int(); or, in the map of zl_arrow_batches(), the names of integer columns.

g

A graph; for zl_forward(), also a graph cache from zl_graph_cache().

data

A named list of arrays, one per input, each matching its input's dimensions exactly (a plain vector for a one-dimensional input). NA is refused. Or an iterator from zl_arrow_batches(), whose next batch is written straight into the inputs; zl_forward() then returns NULL once the stream has ended.

Details

zl_forward() writes data into the inputs, runs the graph and returns the outputs as double arrays. The inputs are rewritten in place on every call, so a graph runs any number of times without being rebuilt.

Inputs are single-precision (f32) unless declared with zl_int(), which makes them 32-bit integers (i32) for zl_get_rows() and zl_rope(). Integer indices count from 0, as in 'ggml'.

Value

zl_graph() returns a graph of class zl_graph; zl_int() an input specification; zl_forward() a named list of double arrays; zl_graph_info() a list describing the graph.

Examples

p <- zl_params()
zl_param(p, "w", c(3, 2))
g <- zl_graph(
  function(x) zl_relu(zl_crossprod(zl_param_tensor(p, "w"), x$input)),
  p,
  inputs = list(input = c(3, 5))
)
out <- zl_forward(g, list(input = matrix(1, 3, 5)))
dim(out$output)

Graphs built once per input shape

Description

zl_graph_cache() wraps zl_graph() for loops whose input shapes vary, such as a decoder whose count of new positions changes. Its graphs are built by zl_forward() the first time it sees a set of input shapes, and reused after. An input given as an R integer vector or array becomes an integer input (see zl_int()); any other numeric input is f32.

Usage

zl_graph_cache(build, p, loss = NULL, outputs = NULL)

## S3 method for class 'zl_graph_cache'
print(x, ...)

Arguments

build

A function of one argument, the named list of inputs, returning a tensor or a named list of tensors.

p

The parameter store whose parameters build() uses.

loss

The name of a scalar output to train on (see the training functions); NULL for none.

outputs

The names of the outputs to keep, of those build() returns; NULL for all.

x

A graph cache.

...

Unused.

Details

When the store's and the cached graphs' memory together would pass getOption("zulm.max_bytes"), the graphs used least recently are freed first; the graph just built is kept.

Value

A graph cache, of class zl_graph_cache, for zl_forward(). length() gives the number of graphs it holds.

Examples

p <- zl_params()
zl_param(p, "w", c(3, 2))
gc <- zl_graph_cache(function(x) zl_crossprod(zl_param_tensor(p, "w"), x$input), p)
dim(zl_forward(gc, list(input = matrix(1, 3, 5)))$output)
dim(zl_forward(gc, list(input = matrix(1, 3, 7)))$output)
length(gc)

Initialisers for parameters

Description

Each returns a description of how zl_param() fills a new parameter. Random draws come from 'zurand' under a key derived from the session key and the parameter's name, so they do not depend on the order in which parameters are declared, and adding a parameter does not change the values of the others.

Usage

zl_init_normal(sd = 0.02)

zl_init_uniform(a)

zl_init_zeros()

zl_init_ones()

Arguments

sd

Standard deviation of a normal distribution with mean zero.

a

Half-width of a uniform distribution on ⁠(-a, a)⁠.

Value

An object of class zl_init.

Examples

p <- zl_params()
zl_param(p, "w", c(4, 3), init = zl_init_normal(sd = 0.1))
zl_param(p, "b", 3, init = zl_init_zeros())
zl_param_get(p, "b")

Random draws inside a graph

Description

zl_noise_normal() and zl_noise_uniform() are tensors of draws from the stream named stream, made anew at each training step: at step s of a trainer (1 for the first) element i (in R's order, counting from 0) is position offset + i of the stream at step s. Outside training, zl_forward() uses the trainer's last step, or 0. The values do not depend on the thread count, and equal zl_rng_normal() and zl_rng_uniform() for the same stream, step and positions. Use offset to keep the draws of a split batch the same: a second half of a batch starts at the first half's size.

Usage

zl_noise_normal(dim, stream, offset = 0)

zl_noise_uniform(dim, stream, offset = 0)

Arguments

dim

Dimensions: one to four positive whole numbers.

stream

The stream's name.

offset

The position of the first value.

Details

They have no gradient, and none is needed: nothing flows back into a draw.

Value

A tensor.

Examples

p <- zl_params()
g <- zl_graph(function(x) x$a + zl_noise_normal(c(2, 3), "eps"), p,
              inputs = list(a = c(2, 3)))
zl_forward(g, list(a = matrix(0, 2, 3)))$output

Parameter stores

Description

A parameter store holds named tensors of up to four dimensions. Its memory belongs to the 'ggml' library, outside R's heap, and is freed when the store is garbage collected. Stores cannot be saved with saveRDS(): a restored store is invalid (zulm_stale_error); use zl_save() and zl_load().

Usage

zl_params()

zl_param(
  p,
  name,
  dim,
  init = zl_init_normal(sd = 0.02),
  type = c("f32", "f16", "bf16")
)

zl_param_get(p, name)

zl_param_set(p, name, value)

zl_param_names(p, types = FALSE)

zl_param_count(p)

zl_param_tensor(p, name)

Arguments

p

A parameter store from zl_params() or zl_load().

name

The parameter's name: a string of 1 to 63 bytes, unique in the store.

dim

Its dimensions: one to four positive whole numbers.

init

How to fill it: see zl_init_normal().

type

The storage type: "f32", "f16" or "bf16".

value

An array of dim(value) equal to the parameter's dimensions, or a vector of the right length for a one-dimensional parameter. NA is refused.

types

For zl_param_names(): TRUE returns the parameters' storage types, named by parameter.

Details

zl_param() adds a parameter. Its values are stored as type: "f32" (single precision, the default), or "f16" and "bf16" (half precision, for weights that are only read). R doubles are rounded to the nearest representable value; values beyond the type's range become infinite with a zulm_range_warning.

Half precision costs more than storage: 'ggml' converts the activations to the weight's type before a product, so zl_crossprod() with an f16 weight differs from the f32 product by about 1e-3 of the output's scale (2e-4 in a build for the local CPU with half-precision arithmetic, see the README), and with a bf16 weight by about 2e-3 to 3e-3. Results that must match a reference closely need f32 weights.

An R array of dim = c(d1, d2, d3, d4) is stored with the first index fastest, as R stores it, so values move without reordering.

Value

zl_params() returns an empty store. zl_param() and zl_param_set() return the store invisibly. zl_param_get() returns a double vector or array; zl_param_names() the names in the order added; zl_param_count() the total number of values; zl_param_tensor() a handle for use when building a graph, for a parameter or a state tensor (zl_state()).

Examples

p <- zl_params()
zl_param(p, "w", c(3, 2))
zl_param(p, "b", 2, init = zl_init_zeros())
zl_param_names(p)
zl_param_count(p)
zl_param_set(p, "b", c(0.5, -0.5))
zl_param_get(p, "b")

Random draws, in R

Description

zl_rng_uniform() and zl_rng_normal() return the single-precision values that zl_noise_uniform() and zl_noise_normal() give inside a graph for the same stream, step and positions: positions offset to offset + prod(dim) - 1 of the stream named stream at step step. Uniforms lie strictly inside (0, 1); normals have mean 0 and standard deviation 1.

Usage

zl_rng_uniform(dim, stream, step = 0, offset = 0)

zl_rng_normal(dim, stream, step = 0, offset = 0)

Arguments

dim

Dimensions: one to four positive whole numbers.

stream

The stream's name.

step

The step number (a trainer's step count; 0 for none).

offset

The position of the first value.

Details

The values are 'zurand”s, rounded to single precision: a uniform is rounded towards zero (so it never becomes 1), a normal to nearest. With the session key k, a uniform equals zurand::rng_uniform( zurand::rng_fold(zurand::rng_fold(k, stream), step), n, offset = offset) so rounded.

Value

A double vector or array of dimensions dim.

Examples

zl_seed(1)
zl_rng_uniform(c(2, 3), "noise")
zl_rng_normal(4, "noise", step = 2)

safetensors files

Description

safetensors is the format PyTorch-trained weights travel in. zl_safetensors_read() returns a file's tensors as R arrays; zl_load_safetensors() fills a store's parameters from one, reading each tensor straight into the store; zl_save_safetensors() writes a store.

Usage

zl_safetensors_read(path, names = NULL)

zl_load_safetensors(p, path, map = NULL)

zl_save_safetensors(p, path, type = c("f32", "f16", "bf16"), metadata = list())

Arguments

path

The file.

names

Tensors to read; NULL for all.

p

A parameter store.

map

NULL, or a named character vector from the file's tensor names (the names) to the store's parameter names (the values). Without one, tensors fill parameters of the same name.

type

The type to write: "f32", "f16" or "bf16".

metadata

A named list of strings, written as the header's ⁠__metadata__⁠.

Details

Shapes are row-major in the file, so a tensor of shape = c(s1, ..., sk) is an R array of dim = c(sk, ..., s1) holding the same bytes: PyTorch's nn.Linear weight of shape ⁠[out, in]⁠ is ⁠c(in, out)⁠, the layout of zl_linear(), with no transposition.

Types: F32, F16 and BF16 values are read as single precision; F64 is rounded to single precision (with a zulm_range_warning if a value overflows); I32 and I64 are read as integers by zl_safetensors_read(). A parameter declared type = "f16" or "bf16" keeps a matching tensor as it is and rounds others to its type. Other types are refused.

The header is checked before any data is read: its length, every tensor's offsets (in range, in order, without overlap, covering the data) and every size against its type and shape. A failure is zulm_file_error.

Value

zl_safetensors_read(): a named list of arrays, with the file's metadata as the "metadata" attribute. zl_load_safetensors(): the names of the parameters it filled, invisibly. zl_save_safetensors(): path, invisibly.

Examples

p <- zl_params()
zl_param(p, "lin.weight", c(3, 2))
path <- tempfile(fileext = ".safetensors")
zl_save_safetensors(p, path, metadata = list(source = "example"))
str(zl_safetensors_read(path))
q <- zl_params()
zl_param(q, "w", c(3, 2), init = zl_init_zeros())
zl_load_safetensors(q, path, map = c(lin.weight = "w"))
identical(zl_param_get(q, "w"), zl_param_get(p, "lin.weight"))
unlink(path)

Save and load parameters as GGUF

Description

zl_save() writes every parameter of a store, and optional metadata, to a GGUF file, the format of the 'ggml' library, which other tools (llama.cpp, the 'gguf' Python package) read. zl_load() reads one into a new store, with every tensor in single precision unless keep_types is TRUE.

Usage

zl_save(p, path, type = c("f32", "f16", "bf16"), metadata = list())

zl_load(path, keep_types = FALSE)

Arguments

p

A parameter store.

path

The file to write or read.

type

The type tensors are written as: "f32", "f16" or "bf16". Half-precision types halve the file and round each value.

metadata

A named list of key-value pairs to store with the tensors: each value a character, integer, double or logical vector without NA. Keys starting with zulm. and the key general.alignment are reserved.

keep_types

For zl_load(): FALSE widens every tensor to f32; TRUE keeps f16 and bf16 tensors in their type in memory (see zl_params() for the cost in precision).

Details

To save a trainer with its optimiser state, use zl_trainer_save(). zl_load() reads the parameters of such a file and leaves out the optimiser state.

Tensor dimensions follow R's order: a GGUF tensor of ⁠ne = {d1, d2}⁠ is an R matrix of dim = c(d1, d2), which NumPy reads as an array of shape ⁠(d2, d1)⁠ holding the same bytes.

Value

zl_save() returns path invisibly. zl_load() returns a parameter store whose "metadata" attribute is the file's metadata as a named list.

Examples

p <- zl_params()
zl_param(p, "w", c(3, 2))
path <- tempfile(fileext = ".gguf")
zl_save(p, path, metadata = list(model = "example", width = 3L))
q <- zl_load(path)
all.equal(zl_param_get(q, "w"), zl_param_get(p, "w"))
attr(q, "metadata")$model
unlink(path)

The session's random-number key

Description

Every random number zulm draws (parameter initialisation, noise inside graphs, zl_rng_uniform() and zl_rng_normal()) comes from 'zurand' under a key derived from the session key and a name. zl_seed() sets the session key from a whole number, or from a key made with zurand::rng_key() or zurand::rng_fold(); with no argument it returns the current key. Until it is set, the key is drawn once from R's generator, so set.seed() before the first draw governs a session.

Usage

zl_seed(seed = NULL)

Arguments

seed

NULL to get the key; a whole number from 0 to .Machine$integer.max, or a zurand rng_key of length one, to set it.

Value

The session key; when setting, the previous key, invisibly.

Examples

old <- zl_seed(42)
zl_rng_normal(3, "example")
zl_seed(old)

State tensors

Description

A state tensor is a persistent f32 tensor in a parameter store that graphs read like a parameter and write with zl_state_write(). It is never trained and never saved: zl_save() and zl_save_safetensors() leave it out, and zl_param_names() and zl_param_count() do not count it. A key-value cache for incremental decoding is two state tensors per layer, of a fixed capacity.

Usage

zl_state(p, name, dim)

zl_state_get(p, name)

zl_state_set(p, name, value, offset = NULL)

zl_state_write(s, x, rows)

Arguments

p

A parameter store from zl_params() or zl_load().

name

The state's name: a string of 1 to 63 bytes, unique in the store.

dim

Its dimensions: one to four positive whole numbers.

value

For zl_state_set(): without offset, an array of the state's dimensions; with offset, a numeric vector.

offset

NULL, or the position, counted from 0, at which to start writing value.

s

A state tensor inside build(), from zl_param_tensor().

x

A tensor whose first, third and fourth dimensions are the state's.

rows

An integer input of one index per second-dimension slice of x.

Details

zl_state() declares a state of zeros. Inside build(), take a handle on it with zl_param_tensor(). zl_state_write(s, x, rows) writes the second-dimension slices of x into the slices of s that rows names, each time the graph runs. rows must be an integer input declared with zl_int(), counting from 0, and no row may appear twice in one run. The write returns s after the write: read the state through it, so the read follows the write. A graph that writes state cannot be trained.

zl_state_set() without offset replaces the whole state, as zl_param_set() does, which resets it. With offset, it writes the values of value in order from that position of the state's values, counted from 0 with the first index fastest, as R stores an array. A write that would reach past the state's end is an error. A sliding window shifts this way without rebuilding a graph.

Value

zl_state() and zl_state_set() return the store invisibly; zl_state_get() a double array; zl_state_write() the state tensor after the write.

Examples

p <- zl_params()
zl_state(p, "cache", c(2, 4))
g <- zl_graph(
  function(x) {
    s <- zl_state_write(zl_param_tensor(p, "cache"), x$new, x$rows)
    zl_sum(s)
  },
  p,
  inputs = list(new = c(2, 1), rows = zl_int(1))
)
zl_forward(g, list(new = matrix(1, 2, 1), rows = 0L))
zl_forward(g, list(new = matrix(2, 2, 1), rows = 3L))
zl_state_get(p, "cache")
zl_state_set(p, "cache", c(9, 9), offset = 2)
zl_state_get(p, "cache")

Threads

Description

zl_threads() sets how many threads 'ggml' computes with, for every graph, trainer and gradient of the session, and returns the previous number; with no argument it returns the current one. It starts at 1. A request is capped at the number of available cores and, while ⁠R CMD check⁠ limits cores (⁠_R_CHECK_LIMIT_CORES_⁠), at 2: too many threads on too few cores make 'ggml' many times slower.

Usage

zl_threads(n = NULL)

Arguments

n

NULL, or the number of threads: a positive whole number.

Details

One pool of threads serves the session; it is recreated when the number changes, and in a process forked from this one. Results are identical at any number of threads (see the package documentation on determinism). A computation can be interrupted between two of its operations; it then signals a condition of class zulm_interrupt, which also inherits interrupt.

Value

The number of threads; when setting, the previous number, invisibly.

Examples

old <- zl_threads(2)
zl_threads()
zl_threads(old)

Train a graph

Description

zl_trainer() prepares a graph with a loss for training with an optimiser: it checks that every operation between a parameter and the loss has a gradient (zulm_unsupported_backward names the one that has not, and the call that made it), and builds the gradient and optimiser graphs once, through 'ggml-opt'. Every f32 parameter the loss depends on is trained; half-precision parameters cannot be. 'ggml-opt' holds each training graph in 2048 nodes, its operations and leaves together: a larger one is zulm_invalid_argument, whose fields nodes and limit give the count needed and the limit.

Usage

zl_trainer(g, opt, accumulate = 1L, clip_norm = NULL)

zl_step(tr, data, lr = NULL)

zl_grad(tr, name)

Arguments

g

A graph from zl_graph() with a loss.

opt

An optimiser from zl_adamw() or zl_sgd().

accumulate

The number of batches whose gradients are summed before each update.

clip_norm

NULL, or the largest joint L2 norm of the gradients at an update.

tr

A trainer.

data

A named list of arrays for the graph's inputs, as for zl_forward(), or an iterator from zl_arrow_batches().

lr

The learning rate of this step; NULL for the optimiser's.

name

A parameter's name.

Details

zl_step() writes a batch into the graph's inputs, computes the loss and the gradients, and, every accumulate calls, updates the parameters. It returns the loss of the batch; a loss that is not finite gives a zulm_nonfinite_warning. With clip_norm, each update first scales all gradients together so that their joint L2 norm is at most clip_norm.

zl_grad() returns the gradient of the loss with respect to one parameter, at the parameters' current values, on the inputs last written by zl_step() or zl_forward().

zl_trainer_save() saves a trainer's parameters and optimiser state, and zl_reset() clears the state. If a step is interrupted the state is undefined: call zl_reset() before going on.

Value

zl_trainer() returns a trainer; zl_step() the loss, a number (NULL when data is an iterator whose stream has ended); zl_grad() an array of the parameter's dimensions.

Examples

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"
)
tr <- 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)
for (i in 1:200) loss <- zl_step(tr, list(x = x, y = y))
loss
zl_param_get(p, "w")

Save, load and reset a trainer's optimiser state

Description

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.

Usage

zl_trainer_save(tr, path)

zl_trainer_load(tr, path)

zl_reset(tr)

Arguments

tr

A trainer from zl_trainer().

path

The file to write or read.

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.

Value

zl_trainer_save() returns path invisibly; zl_trainer_load() and zl_reset() the trainer, invisibly.

See Also

zl_trainer(), zl_save().

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)))
unlink(path)

Arithmetic, reductions and elementwise functions on tensors

Description

Inside build(), +, -, * and / combine tensors elementwise with broadcasting: one operand's dimensions must each divide the other's, as in 'ggml'. A number on either side is a scale or an added constant. zl_sum() sums every element to a scalar; zl_sum_rows() and zl_mean_rows() reduce the first dimension to 1; zl_cumsum() takes cumulative sums along it. The others apply elementwise.

Usage

zl_scale(x, s)

zl_sum(x)

zl_sum_rows(x)

zl_mean_rows(x)

zl_cumsum(x)

zl_sqr(x)

zl_sqrt(x)

zl_exp(x)

zl_log(x)

zl_abs(x)

zl_sin(x)

zl_cos(x)

zl_relu(x)

zl_silu(x)

zl_softplus(x)

zl_sigmoid(x)

zl_tanh(x)

zl_gelu(x, approximate = c("none", "tanh"))

zl_swiglu(gate, up)

Arguments

x

A tensor.

s

A number.

approximate

For zl_gelu(): "none" for the exact form with the error function (accurate to single precision), "tanh" for the tanh approximation, which 'ggml' evaluates through a half-precision table (accurate to about 1e-3).

gate, up

Tensors of the same shape.

Details

zl_cumsum(), zl_gelu() and zl_sigmoid() have no gradient: they serve inference and sampling graphs, and training refuses them on a gradient path.

Value

A tensor.

Examples

p <- zl_params()
g <- zl_graph(
  function(x) list(
    y = zl_sum_rows(zl_sqr(x$a - 1)),
    z = 2 * zl_exp(x$a) + 1
  ),
  p,
  inputs = list(a = c(3, 2))
)
zl_forward(g, list(a = matrix(1:6, 3, 2)))

Attention pieces and normalisation

Description

zl_softmax() normalises each column (the first dimension) after multiplying by scale and adding mask, an additive f32 tensor whose first two dimensions are x's and whose third and fourth are 1 or x's, so one mask serves every head. zl_causal_mask() sets to -Inf every element of each matrix whose row index exceeds its column index, so that for scores of dims c(n_kv, n_q, ...) a query sees only keys at or before it.

Usage

zl_softmax(x, mask = NULL, scale = 1)

zl_causal_mask(x)

zl_rope(x, pos, n_dims, base = 10000, mode = c("interleaved", "half"))

zl_rms_norm(x, eps = 1e-05)

zl_layer_norm(x, eps = 1e-05)

Arguments

x, mask

Tensors.

scale

A number.

pos

An integer input of positions.

n_dims

The number of leading dimensions to rotate: even, at most head_dim.

base

The frequency base.

mode

"interleaved" or "half".

eps

Added to the mean square, a positive number.

Details

zl_rope() applies rotary positions to x of dims c(head_dim, heads, n, ...) with integer positions pos of length n (an input declared with zl_int()). mode = "interleaved" rotates adjacent pairs ('ggml”s default and Toto's convention); mode = "half" rotates the first half against the second (TimesFM, Chronos-2, most Hugging Face checkpoints). n_dims below head_dim rotates the leading n_dims only. head_dim must be even.

zl_rms_norm() divides each column by its root mean square; zl_layer_norm() subtracts the column mean first.

Value

A tensor.

Examples

p <- zl_params()
g <- zl_graph(
  function(x) zl_softmax(zl_causal_mask(x$s)),
  p,
  inputs = list(s = c(3, 3))
)
zl_forward(g, list(s = matrix(0, 3, 3)))$output

Losses

Description

Each returns a scalar tensor. zl_cross_entropy(logits, prob) is the cross-entropy between the softmax of each column of logits and the probabilities prob of the same shape, summed over columns and divided by their number, as 'ggml' computes it. zl_mse() and zl_mae() are the mean squared and mean absolute errors over every element.

Usage

zl_cross_entropy(logits, prob)

zl_mse(pred, target)

zl_mae(pred, target)

Arguments

logits, prob, pred, target

Tensors.

Value

A scalar tensor.

Examples

p <- zl_params()
g <- zl_graph(
  function(x) zl_mse(x$pred, x$target),
  p,
  inputs = list(pred = 4, target = 4)
)
zl_forward(g, list(pred = c(1, 2, 3, 4), target = c(1, 2, 3, 6)))$output

Modules

Description

Each constructor declares its parameters in the store p, under names that start with name, and returns a function of tensors to use inside build() (see zl_graph()). Tensors have the feature dimension first: a batch of sequences is c(dim, n, batch).

Usage

zl_linear(p, name, n_in, n_out, bias = TRUE)

zl_embedding(p, name, n, dim)

zl_norm(p, name, dim, type = c("layer", "rms"), affine = TRUE, eps = 1e-05)

zl_attention(p, name, dim, heads = 1L, causal = TRUE)

zl_mlp(p, name, dim, hidden = 4 * dim, act = c("swiglu", "silu"))

zl_block(p, name, dim, heads, causal = TRUE, hidden = 4 * dim)

zl_adaln(p, name, dim, cond_dim)

zl_time_embedding(t, dim, max_period = 10000)

Arguments

p

A parameter store.

name

The prefix of the parameters' names.

n_in, n_out

Input and output widths.

bias

Whether to add a bias.

n

The number of rows of an embedding table.

dim

The feature width.

type

"layer" or "rms".

affine

Whether a normalisation has a learnt scale (and shift).

eps

Added to the variance, a positive number.

heads

The number of attention heads; must divide dim.

causal

Whether position i attends only to positions up to i.

hidden

The MLP's inner width.

act

"swiglu" or "silu".

cond_dim

The width of the conditioning tensor.

t

A tensor of times, of dims c(1, ...).

max_period

The longest period of the embedding.

Details

  • zl_linear(): zl_crossprod(weight, x) + bias, with weight of dims c(n_in, n_out); parameters ⁠<name>.weight⁠ and ⁠<name>.bias⁠, initialised uniformly on ⁠(-1, 1) / sqrt(n_in)⁠ as in PyTorch.

  • zl_embedding(): rows of ⁠<name>.weight⁠, of dims c(dim, n), for integer indices counting from 0 (an input declared with zl_int()); the result has dims c(dim, dim(idx)). Initialised as N(0, 1).

  • zl_norm(): layer or RMS normalisation of each column, then, with affine = TRUE, a scale ⁠<name>.weight⁠ (ones) and, for layer normalisation, a shift ⁠<name>.bias⁠ (zeros).

  • zl_attention(): multi-head self-attention with linear projections ⁠<name>.q⁠, .k, .v and .o, scaled by 1 / sqrt(dim / heads), causal by default.

  • zl_mlp(): down(swiglu(gate(x), up(x))), or down(silu(up(x))) with act = "silu", with linears ⁠<name>.gate⁠, .up and .down.

  • zl_block(): a pre-norm transformer block, h = x + attn(norm1(x)), then h + mlp(norm2(h)), with layer norms.

  • zl_adaln(): adaptive layer normalisation's modulation, function(x, cond) x * (1 + scale(cond)) + shift(cond), with linears ⁠<name>.scale⁠ and ⁠<name>.shift⁠ from cond_dim to dim.

  • zl_time_embedding(): no parameters; the sinusoidal embedding of times t of dims c(1, ...): ⁠cos(t f)⁠ then ⁠sin(t f)⁠ for the dim / 2 frequencies f_k = max_period^(-k / (dim / 2)).

Value

A function of tensors, except zl_time_embedding(), which returns a tensor.

Examples

p <- zl_params()
emb <- zl_linear(p, "in", n_in = 3, n_out = 8)
blk <- zl_block(p, "b1", dim = 8, heads = 2)
g <- zl_graph(function(x) blk(emb(x$x)), p, inputs = list(x = c(3, 5, 2)))
dim(zl_forward(g, list(x = array(0.1, c(3, 5, 2))))$output)

Selection, clipping and triangles

Description

zl_where(mask, a, b) is mask * a + (1 - mask) * b for a mask of 0s and 1s. zl_clamp() limits values to ⁠[lo, hi]⁠. zl_tri() keeps one triangle of each matrix, as lower.tri() and upper.tri() select it, and sets the rest to zero. zl_clamp() has no gradient.

Usage

zl_where(mask, a, b)

zl_clamp(x, lo, hi)

zl_tri(x, type = c("lower", "upper", "lower_strict", "upper_strict"))

Arguments

mask, a, b, x

Tensors.

lo, hi

Numbers.

type

Which triangle: "lower" and "upper" include the diagonal, the ⁠_strict⁠ forms do not.

Value

A tensor.

Examples

p <- zl_params()
g <- zl_graph(
  function(x) zl_tri(zl_clamp(x$m, -1, 1), "lower"),
  p,
  inputs = list(m = c(3, 3))
)
zl_forward(g, list(m = matrix(-4:4, 3, 3)))$output

Products and shapes of tensors

Description

zl_crossprod(a, b) is crossprod(a, b): for a of dims c(K, M) and b of c(K, N) it has dims c(M, N), batched over the third and fourth dimensions (where a's may divide b's). A linear layer stores its weight as c(n_in, n_out) and computes zl_crossprod(w, x); the weight may be stored as f16 or bf16.

Usage

zl_crossprod(a, b)

zl_reshape(x, dim)

zl_permute(x, perm)

zl_t(x)

zl_cont(x)

zl_view(x, dim, offset = 0)

zl_concat(a, b, axis)

zl_pad(x, after)

zl_get_rows(x, idx)

Arguments

a, b, x

Tensors.

dim

New dimensions: one to four positive whole numbers.

perm

A permutation of seq_len(k), with k at least the rank of x and at most 4.

offset

The first element of the view, counting from 0.

axis

The dimension to join along, from 1 to 4.

after

Numbers of zeros to append after each dimension.

idx

An integer input (declared with zl_int()) of column indices.

Details

zl_reshape() gives new dimensions with the same number of elements; zl_permute() reorders dimensions as aperm() does; zl_t() transposes the first two; zl_cont() makes a permuted tensor contiguous (operations do it themselves when they need to); zl_view() is a window of prod(dim) elements from position offset (counting from 0) of a contiguous tensor. zl_concat() joins two tensors along axis, zl_pad() appends zeros after each dimension, and zl_get_rows() selects columns of a matrix (rows in 'ggml”s terms) by an integer input, counting from 0. zl_pad() has no gradient.

Value

A tensor.

Examples

p <- zl_params()
zl_param(p, "w", c(4, 2))
g <- zl_graph(
  function(x) zl_t(zl_crossprod(zl_param_tensor(p, "w"), x$x)),
  p,
  inputs = list(x = c(4, 3))
)
dim(zl_forward(g, list(x = matrix(1, 4, 3)))$output)

Build and runtime information

Description

Reports the vendored ggml version, the variant loaded for this CPU, the variants installed and usable, the native-build hooks recorded at install time, and the CPU features ggml was compiled for.

Usage

zulm_info()

Details

A variant is the whole compiled library built for one instruction-set level: on x86-64 "baseline", "sse42" and "avx2", on arm64 "neon", and "native" when the package was installed with the ZULM_CFLAGS and ZULM_CXXFLAGS hooks set. The best usable variant is loaded when the package is; set options(zulm.variant =) before loading it to force another.

Value

A named list.

Examples

info <- zulm_info()
info$variant
info$ggml_version

Conditions signalled by zulm

Description

Every error zulm signals inherits zulm_error, and every warning zulm_warning, so a handler can catch them all or one class at a time with tryCatch() or withCallingHandlers().

Details

Errors:

  • zulm_invalid_argument: an argument of the wrong kind or value.

  • zulm_shape_error: dimensions that do not fit; carries op, the shapes and the R call where an operation is involved.

  • zulm_type_error: a tensor or value type that is not accepted.

  • zulm_unsupported_backward: an operation without a gradient on a gradient path; carries op.

  • zulm_memory_error: an allocation beyond getOption("zulm.max_bytes") (4 GiB by default); carries requested and allowed, in bytes.

  • zulm_engine_error: an assertion of the ggml library caught while a graph was being built; carries ggml_message. The graph is discarded.

  • zulm_interrupt: a computation stopped by a user interrupt; also inherits interrupt.

  • zulm_file_error: a GGUF or safetensors file that cannot be read or written.

  • zulm_arrow_error: an Arrow stream with an unsupported type, a null, a dictionary or a stream failure; carries column and row.

  • zulm_companion_error: a companion package whose interface lacks something zulm needs.

  • zulm_stale_error: an object that is no longer valid, because it was restored from a saved R session or created by a variant no longer in use.

  • zulm_internal_error: a bug in zulm.

Warnings:

  • zulm_range_warning: values beyond the range of the storage type, which became infinite.

  • zulm_nonfinite_warning: a training step whose loss is not finite.

Examples

p <- zl_params()
tryCatch(
  zl_param_get(p, "missing"),
  zulm_invalid_argument = function(e) conditionMessage(e)
)