santoku
santoku

santoku

A Lua framework for building applications end to end

Lua 5.1 from the build system to the server to the browser. Every example on this site runs in your browser. Edit one and run it.


santoku targets Lua 5.1, because 5.1 is the version its platforms actually share. LuaJIT implements 5.1 and OpenResty embeds LuaJIT, so server code, client code and the build harness all run the same language. Compiled to WebAssembly, the 5.1 core is smaller to embed, and its single number type sidesteps the integer and float split introduced in 5.3, which keeps numeric values crossing the JavaScript boundary simple. Support for newer versions is meant to come from compatibility shims layered over the 5.1 core rather than version branches in the tree; contributions and design ideas for that layer are welcome.

santoku-learn

View on LuaRocks

machine learning toolkit: pooled count-based experts for classification, label sets, regression, span tagging and byte-level language models, plus n-gram tokenization, gazetteer matching and dense reranking

santoku-learn fits count-based experts on text or dense columns and pools their outputs with a Newton-fit mixer. santoku.learn.pool is the one entry point for classification, label sets, regression, span tagging and byte-level language models. The rock also ships the tokenizer, aho, gaz, retrieval and dataset modules.

Details
  • Targets and dense inputs are santoku-matrix types: csr label rows, mtx dense columns and spans. Text inputs are Lua strings.
  • tokenizer and aho ship in the browser bundle as WASM builds, so their examples run on this page.
  • The pool, gazetteer, retrieval and dataset cards are display-only, since they read training corpora from disk.
  • The pool cards distill the rock's regression suites, under test/spec/santoku/learn/regress in its source tarball.
  • The regression suites are adult, banking77, conll-full-stack, conll-gaz, eurlex, imdb, mnist-mix2, newsgroups, protein, ptb and shakespeare.
  • Modules under santoku.learn.pool.* are internal. Call pool.fit, pool.load and the model methods.
  • On native builds the C modules run in parallel with OpenMP. The rock links no BLAS or LAPACK and has no CUDA build.

Pool models

Fit, score and reload

pool.fit fits every expert on the input it names, then a mixer over the experts' outputs. It returns a model and a stats table. The example is the banking77 suite.

local pool = require("santoku.learn.pool")
local ds = require("santoku.learn.dataset")
local fs = require("santoku.fs")
local train, test_set = ds.read_banking77("test/res/banking77")
local m, stats = pool.fit({
  inputs = { text = { texts = train.texts } },
  targets = train.labels,
  seed = 1,
  experts = {
    { name = "char", kind = "bns", input = "text", level = "chars", order = 5 },
    { name = "word", kind = "bns", input = "text", level = "words", order = 3 },
    { name = "cnb_pos", kind = "cnb", from = { "char" }, salience = "pos" },
    { name = "vote_pos", kind = "vote", from = { "char" }, salience = "pos" },
    { name = "geo_word_pos", kind = "geo", from = { "word" }, salience = "pos" },
    { name = "fc_word_256", kind = "fc", from = { "word" }, bins = 256, trees = 100 },
    { name = "stack", kind = "stack", trees = 400 },
  },
})
print("mixer inputs:", #stats.names, "train loss:", stats.train_loss)
local test_inputs = { text = { texts = test_set.texts } }
local acc = m:score(test_inputs, { targets = test_set.labels })
print("test accuracy:", acc)
local picks = m:predict(test_inputs)
print("predicted rows:", picks:size())
m:persist("banking77.pool")
m:destroy()
local m2 = pool.load("banking77.pool")
print("reloaded matches:", m2:score(test_inputs, { targets = test_set.labels }) == acc)
m2:destroy()
fs.rmdirs("banking77.pool")
Illustrative: runs outside the browser.
Details
KeyHolds
inputsa table from input name to input
targetsthe labels, spans or values to fit, or nil for a language model
expertsthe expert list, at least one
seeda whole number, 1 by default
n_typesthe span type count, tags head only
words{ pattern, boundary }, the word pattern and the boundary bytes
groupsan ivec with one group id per row; a group's rows share a fold
candidates{ input, n_types, experts }, a second stage over candidate spans
  • Any other key raises "pool: pool.fit takes no such key".
  • Every expert carries a unique name and a kind.
  • cnb, vote, geo, fc, stack and segment experts read earlier experts and take no input. Every other expert names the input it reads.
  • The targets and the expert kinds pick the head.
targetsHeadTakes
niltext: next-byte language modelwords
a spans set with s, e and tytags: span taggern_types, words
a csr of label rows, any expert other than forestdocs: text classifierwords, groups, candidates
a csr of label rows, forest experts onlydense: forest classifiergroups
an n x 1 f64 mtxdense: forest regressiongroups
  • An option the head doesn't take raises "pool.fit: this head takes no such option".
  • The csr's n_cols is the label count. The mixer's Newton fits stop at a decrement of 1e-10 or after 50 iterations.
Model callReturns
m:score(inputs, { targets })the head's score and a metrics table
m:predict(inputs)the head's predictions
m:probs(inputs)an f32 mtx of probabilities, one row per input row, on classifiers
m:variance(inputs)a dvec of predictive variances, on regression
m:generate(g)sampled text, on the text head only
m:persist(dir)writes the model as a directory
m:destroy()frees the model
  • pool.load(dir) reads a persisted model. Remove the directory with fs.rmdirs(dir).
  • pool.load raises "pool.load: unsupported version (refit required)" on a directory that another format version wrote.
  • stats.experts holds one entry per expert, with its name, kind, inputs and fit seconds s.
  • stats.names and stats.weights hold each mixer input's name and weight, in the same order.
  • stats.newton is the mixer's Newton log, one { iter, loss, decrement, step, halvings } per iteration. stats.stop names the stop rule and stats.train_loss is the last loss.
  • read_banking77 returns train and test, each { n, n_labels, texts, labels }.

Document experts

A docs fit reads an input { texts } with one string per row. Its bns experts count n-grams, and the cnb, vote, geo and fc experts listed after them read those counts. The example is the imdb suite.

local pool = require("santoku.learn.pool")
local ds = require("santoku.learn.dataset")
local arr = require("santoku.array")
local train, test_set = ds.read_imdb("test/res/aclImdb")
local experts = {
  { name = "char", kind = "bns", input = "text", level = "chars", order = 5 },
  { name = "word", kind = "bns", input = "text", level = "words", order = 3 },
}
for _, s in ipairs({ "char", "word" }) do
  for _, kv in ipairs({ { "cnb", "pos" }, { "cnb", "label" }, { "vote", "pos" }, { "geo", "pos" } }) do
    local name = kv[1] .. "_" .. s .. "_" .. kv[2]
    arr.push(experts, { name = name, kind = kv[1], from = { s }, salience = kv[2] })
  end
end
for _, sb in ipairs({ { "char", { 64, 1024 } }, { "word", { 64, 256, 1024 } } }) do
  for _, b in ipairs(sb[2]) do
    arr.push(experts, { name = "fc_" .. sb[1] .. "_" .. b, kind = "fc", from = { sb[1] }, bins = b, trees = 100 })
  end
end
arr.push(experts, { name = "stack", kind = "stack", trees = 400 })
local m, stats = pool.fit({
  inputs = { text = { texts = train.texts } },
  targets = train.labels,
  experts = experts,
  seed = 1,
})
for _, e in ipairs(stats.experts) do
  print(e.name, e.kind, e.s)
end
print("test accuracy:", m:score({ text = { texts = test_set.texts } }, { targets = test_set.labels }))
m:destroy()
Illustrative: runs outside the browser.
Details
KindKeysFits
bnsinput, level = "chars" or "words", order, optional classesn-gram counts up to order
cnbfrom, optional saliencecomplement naive Bayes
votefrom, optional saliencen-gram votes
geofrom, optional saliencea count model with a fitted temperature, one label per row
fcfrom, bins, treesbins cluster bins over one bns expert, with a forest of trees trees
stacktreesa forest over the outputs of the experts before it
forestinput, trees, optional stages, columns and patcha forest on a dense input
  • order is required on every bns expert, a whole order of at least 1.
  • classes lists ascending word class counts, each from 2 to below half the train vocabulary. The bns expert then counts n-grams over each count's word classes. classes needs level = "words".
  • from lists bns experts named earlier in the list. An fc expert's from names exactly one, with no classes or one class count.
  • salience picks the bns stream's view: "pos", "neg" or "label". Unset reads the plain view. A geo expert raises on "label".
  • With two labels, neg reads the pos view, and so does a vote expert's label view. An expert that reads the same view of the same streams as an earlier one raises "pool: this expert copies an earlier one".
  • Only stack experts follow a stack expert.
  • With one label per row, score returns accuracy and { n, experts }.
  • score(inputs, { targets, experts = true }) also fills experts. Without a stack expert, experts holds { acc, picks } for each fc, cnb, vote and geo expert, and the caller destroys each picks ivec. experts = true raises on label sets.
  • predict returns an ivec of class ids.
  • words.pattern sets the word pattern, "[A-Za-z0-9]+" by default. The pattern must not match the newline, since the fit joins the texts with newlines.
  • words.boundary is one byte on a docs fit.

Label sets

When any targets row holds zero or several labels, the docs head fits a logistic mixer per label and a decision threshold. score then returns micro F1. The example is the eurlex suite, with one input per document field.

local pool = require("santoku.learn.pool")
local ds = require("santoku.learn.dataset")
local arr = require("santoku.array")
local dir = "test/res/eurlex57k"
local zones = { "title", "header", "recitals" }
local train, _, test_set = ds.read_eurlex57k(dir)
local train_inputs, test_inputs = { text = { texts = train.texts } }, { text = { texts = test_set.texts } }
local experts = { { name = "word", kind = "bns", input = "text", level = "words", order = 3 } }
for _, z in ipairs(zones) do
  local ztrain, _, ztest = ds.read_eurlex57k(dir, { z })
  train_inputs[z], test_inputs[z] = { texts = ztrain.texts }, { texts = ztest.texts }
  arr.push(experts, { name = z, kind = "bns", input = z, level = "words", order = 3 })
  arr.push(experts, { name = "cnb_" .. z, kind = "cnb", from = { z }, salience = "pos" })
end
arr.push(experts, { name = "vote_pos", kind = "vote", from = { "word" }, salience = "pos" })
arr.push(experts, { name = "fc_word_256", kind = "fc", from = { "word" }, bins = 256, trees = 100 })
arr.push(experts, { name = "stack", kind = "stack", trees = 400 })
local m, stats = pool.fit({ inputs = train_inputs, targets = train.labels, experts = experts, seed = 1 })
print("threshold:", stats.threshold, "train micro F1:", stats.threshold_f1)
local f1, r = m:score(test_inputs, { targets = test_set.labels })
print("test micro F1:", f1, "precision:", r.precision, "recall:", r.recall)
local sets = m:predict(test_inputs)
print("label set rows:", (sets:shape()))
m:destroy()
Illustrative: runs outside the browser.
Details
  • The fit picks the threshold with the best micro F1 on the train rows. stats.threshold holds the threshold, and stats.threshold_f1 its train micro F1.
  • score returns micro F1 and { precision, recall, threshold, n }.
  • predict returns a csr with each row's label set, and probs one probability per label.
  • geo experts raise on label sets. A label-set stack comes last in the list.
  • Every input holds one row per text. Experts on different inputs feed one mixer.
  • read_eurlex57k(dir, fields) returns train, dev and test, each with texts and labels as a csr of label sets. fields lists the text fields joined into each text, { "title", "header", "recitals", "main_body" } by default.
  • test/res/Makefile's eurlex57k target unpacks archive.org's EURLEX57K dataset.zip, the published 45000 / 6000 / 6000 split.

Forests on dense columns

A forest expert reads a dense input { dense, categorical }. A fit whose experts are all forests goes to the dense head. The example is the adult suite.

local pool = require("santoku.learn.pool")
local ds = require("santoku.learn.dataset")
local train, test_set = ds.read_adult("test/res/adult")
local function table_of (s)
  return { table = { dense = s.dense, categorical = s.bits } }
end
local m = pool.fit({
  inputs = table_of(train),
  targets = train.labels,
  experts = { { name = "forest", kind = "forest", input = "table", trees = 64, columns = "each" } },
  seed = 1,
})
print("test accuracy:", m:score(table_of(test_set), { targets = test_set.labels }))
print("probability rows, cols:", m:probs(table_of(test_set)):shape())
m:destroy()
Illustrative: runs outside the browser.
Details
  • dense is an f32 mtx with finite values, and categorical is a csr of bits with the same rows. A dense input holds dense, categorical or both.
  • Without columns, one forest splits on every dense column and bit. With columns = "each", each dense column gets its own forest, and the bits get one more forest.
  • columns = "each" needs at least one dense column. Any other value raises.
  • trees is required: each forest grows that many trees.
  • stages is the boosting stage count, 1 by default, and above 1 on regression only.
  • The forest reads out at a ladder of depths, then at its deepest tree depth. Each depth gives one mixer input, and stats.experts[i].depths lists them.
  • The forest's train outputs are out of bag.
  • A dense classifier takes one class per row. score returns accuracy and { n }, and predict returns an ivec of class ids.
  • read_adult returns train, test and meta. Each split holds n, bits, dense and labels, with the bits and dense columns from a booleanizer fit on the train rows.

Patch codes on image rows

A forest expert's patch turns each dense row, read as a w x h image, into code counts over a grid of cells before the forest fits. The example is the mnist-mix2 suite.

local pool = require("santoku.learn.pool")
local ds = require("santoku.learn.dataset")
local train, test_set = ds.read_mnist("test/res/mnist")
local m = pool.fit({
  inputs = { pixels = { dense = train.dense } },
  targets = train.labels,
  experts = {
    { name = "forest", kind = "forest", input = "pixels", trees = 512 },
    { name = "patch", kind = "forest", input = "pixels", trees = 512,
      patch = { code = "pixels", w = 28, h = 28, size = 3, levels = 2, grid = 2 } },
    { name = "grad", kind = "forest", input = "pixels", trees = 512,
      patch = { code = "grad", w = 28, h = 28, bins = 9, grid = 7 } },
  },
  seed = 1,
})
print("test accuracy:", m:score({ pixels = { dense = test_set.dense } }, { targets = test_set.labels }))
m:destroy()
Illustrative: runs outside the browser.
Details
patch.codeKeysCounts
pixelsw, h, size, levels, gridsize x size pixel patches quantized to levels, per grid x grid cell
gradw, h, bins, gridgradient orientations in bins, per grid x grid cell
  • Every patch key is a whole number of at least 1. Any other key raises.
  • w x h is the input's column count.
  • pixels needs 1 <= size <= w and h, levels at least 2, and levels^(size x size) at most 2^24.
  • grad needs w and h at least 3, bins at least 2, and grid at most w - 2 and h - 2.
  • A patch reads one dense input with no categorical bits, on an expert with no columns.
  • Experts with and without patch read the same input and feed one mixer.

Regression

Targets as an n x 1 f64 mtx fit forest regression with a Gaussian mixer. score returns the RMSE and { r2, n }. The example is the protein suite on split 0.

local pool = require("santoku.learn.pool")
local ds = require("santoku.learn.dataset")
local train, test_set = ds.read_protein("test/res/protein", 0)
local m = pool.fit({
  inputs = { table = { dense = train.continuous } },
  targets = train.targets,
  experts = { { name = "forest", kind = "forest", input = "table", trees = 500, stages = 2 } },
  seed = 1,
})
local test_inputs = { table = { dense = test_set.continuous } }
local rmse, r = m:score(test_inputs, { targets = test_set.targets })
print("test rmse:", rmse, "r2:", r.r2)
print("first mean, variance:", m:predict(test_inputs):get(0), m:variance(test_inputs):get(0))
m:destroy()
Illustrative: runs outside the browser.
Details
  • The mixer weights are nonnegative, and stats.names ends with linear and prior.
  • stages above 1 adds boosting stages. Each stage fits the previous stage's out-of-bag residuals and adds one input per depth.
  • predict returns a dvec of means, and variance a dvec of variances.
  • probs raises on a regression model.
  • read_protein(dir, split) reads the UCI protein rows and one of their five published test splits (0 to 4).
  • Each split is { n, n_features, continuous, targets }. continuous is an f32 mtx and targets the n x 1 f64 mtx of RMSD.

Text and dense together

A docs fit takes forest experts beside its text experts. Each forest reads a dense input with one row per text, and the mixer weighs both kinds. It works with one label or label sets.

local pool = require("santoku.learn.pool")
local ds = require("santoku.learn.dataset")
local mtx = require("santoku.mtx")
local fvec = require("santoku.fvec")
local train = ds.read_20newsgroups("test/res/20news-bydate-train")
local test_set = ds.read_20newsgroups("test/res/20news-bydate-test")
local function codes (path, n)
  return { dense = mtx.create({ data = fvec.load(path), n_rows = n, n_cols = 384 }) }
end
local m, stats = pool.fit({
  inputs = { text = { texts = train.texts }, emb = codes("train.codes", train.n) },
  targets = train.labels,
  experts = {
    { name = "char", kind = "bns", input = "text", level = "chars", order = 5 },
    { name = "word", kind = "bns", input = "text", level = "words", order = 3 },
    { name = "cnb", kind = "cnb", from = { "word" } },
    { name = "emb", kind = "forest", input = "emb", trees = 100 },
  },
  seed = 1,
})
print("forest inputs:", #stats.experts[4].inputs)
local test_inputs = { text = { texts = test_set.texts }, emb = codes("test.codes", test_set.n) }
print("test accuracy:", m:score(test_inputs, { targets = test_set.labels }))
m:destroy()
Illustrative: runs outside the browser.
Details
  • A forest expert in a docs fit takes the forest keys of the dense head, with stages 1.
  • Every input holds one row per text. A row count that differs raises "pool: every input holds one entry per row".
  • score and predict take the same input names, here text and emb.
  • Here train.codes and test.codes hold f32 codes persisted earlier, 384 per text.
  • The dense rows can be any f32 codes. The learn-llama page fits gguf embeddings this way.

Evidence stacks on candidates

A docs fit with one row per candidate span and the candidates option scores candidates in two stages. The second stage fits forests on evidence built from the first stage's out-of-fold probabilities, then keeps the best non-overlapping spans.

local pool = require("santoku.learn.pool")
local function fit (rows, cand, labels)
  return pool.fit({
    inputs = { text = { texts = rows }, cand = cand },
    targets = labels,
    experts = {
      { name = "word", kind = "bns", input = "text", level = "words", order = 3 },
      { name = "cnb", kind = "cnb", from = { "word" } },
      { name = "vote", kind = "vote", from = { "word" } },
    },
    candidates = {
      input = "cand",
      n_types = 11,
      experts = { { name = "evidence", kind = "forest", input = "evidence", trees = 500 } },
    },
    seed = 1,
  })
end
return fit
Illustrative: runs outside the browser.
Details
  • candidates is { input, n_types, experts }. input names the candidates input { spans, surface }, with one spans document per text document and one candidate per targets row.
  • spans holds s and e columns. surface is an ivec with one surface id per candidate.
  • The targets give each candidate a type from 0 to n_types - 1, or n_types to reject it.
  • Each second stage expert reads the input named evidence, built by the fit.
  • Each document's candidates share one fold. A candidates fit takes no groups.
  • stats.candidates holds the second stage's stats and evidence_cols, the evidence width.
  • score takes { targets } with the target spans and returns span F1 and { precision, recall, n }. predict returns a spans set with s, e and ty, one span document per candidate document.
  • probs returns one probability per candidate label.

Span tagging

Span targets fit a BIO tagger: n-gram, window and gazetteer experts, a mixer per tag, then a segment CRF. The input is { texts, docs }. The example is the conll-gaz suite.

local pool = require("santoku.learn.pool")
local ds = require("santoku.learn.dataset")
local gaz = require("santoku.learn.gaz")
local tr, dev, test_set = ds.read_conll2003("test/res/conll2003")
local train = ds.merge_conll2003(tr, dev)
local all = ds.merge_conll2003(train, test_set)
local gz = gaz.create({ texts = all.texts, gold = all.gold, n_types = 4 })
local classes = { 16, 64, 256 }
local m, stats = pool.fit({
  inputs = { text = { texts = train.texts, docs = train.article }, gaz = gz },
  targets = train.gold,
  n_types = 4,
  words = { pattern = "[^ \n]+", boundary = "\n" },
  seed = 1,
  experts = {
    { name = "word", kind = "kn", input = "text", level = "words", order = { forward = 4, reverse = 3 } },
    { name = "sides", kind = "sided", input = "text", level = "words", radius = 4 },
    { name = "char_sides", kind = "sided", input = "text", level = "chars", radius = 14 },
    { name = "class_sides", kind = "sided", input = "text", level = "words", classes = classes, radius = 15 },
    { name = "gaz", kind = "gaz", input = "text", gazetteer = "gaz", radius = 2 },
    { name = "segment", kind = "segment", chains = { "prefix", "suffix", "left", "right", "gaz" }, gazetteer = "gaz" },
  },
})
print("crf train loss:", stats.stage.train_loss)
local test_inputs = { text = { texts = test_set.texts, docs = test_set.article }, gaz = gz }
local f1, r = m:score(test_inputs, { targets = test_set.gold })
print("span F1:", f1, "precision:", r.precision, "recall:", r.recall)
local S = m:predict(test_inputs)
print("span documents:", S:n_docs())
m:destroy()
Illustrative: runs outside the browser.
Details
  • targets is a spans set with columns s, e and ty and one span document per text. n_types counts the span types.
  • docs is an ivec with one document id per text.
  • The tagger labels each word O, or B or I of a type, so it has 1 + 2 x n_types labels.
KindKeys
kninput, level, order = { forward, reverse }, optional classes
sidedinput, level, radius, optional classes
gazinput, gazetteer, optional radius
stacktrees
segmentchains, optional gazetteer
  • level is "chars" or "words". classes lists ascending word class counts, each from 2 to below the train vocabulary, with its square at most the train token count.
  • order gives the kn expert's forward and reverse n-gram orders, each a whole number of at least 1.
  • radius is the context window in units, a whole number of at least 1. Every sided expert takes it. A gaz expert takes it optionally, and with it reads a window of radius units around each word. No other expert takes it.
  • A tagging fit takes exactly one segment expert. Its chains list from surface, prefix, suffix, left, right and gaz, each once. gaz needs the gazetteer key.
  • A tagging fit takes at most one stack expert. It fits trees trees on the mixer's tag probabilities and a second mixer, and the segment CRF reads its output.
  • gazetteer names the input that holds a gaz object. score and predict take that input too.
  • The fit records the gazetteer's gz:id(), its key count and content hash. score and predict raise "pool: the gazetteer differs from the one the model was fit with" on any other gazetteer.
  • stats.stage holds the CRF's names, weights and Newton log, and stats.stack the stack's.
  • score returns span F1 and { precision, recall, n }, where n is the gold span count.
  • predict returns a spans set with s, e and ty, one span document per text. probs returns the tag probabilities, one row per word.
  • words.boundary is one byte on a tagging fit.
  • The conll-gaz gazetteer is built from the test gold on purpose. The conll-full-stack suite drops the gaz expert, adds a stack expert and trains on train alone.

Byte language models

With no targets, pool.fit fits a next-byte model on input { text, lo, hi }. score returns bits per byte, and generate samples text. The example is the shakespeare suite.

local pool = require("santoku.learn.pool")
local fs = require("santoku.fs")
local num = require("santoku.num")
local text = fs.readfile("test/res/tinyshakespeare/input.txt")
local split = num.floor(0.9 * #text)
local ladder = { 16, 64, 256, 1024, 4096, 16384 }
local m, stats = pool.fit({
  inputs = { text = { text = text, lo = 0, hi = split } },
  words = { pattern = "%S+", boundary = "\n" },
  seed = 1,
  experts = {
    { name = "char_kn", kind = "kn", input = "text", level = "chars", order = 7 },
    { name = "char_cache", kind = "cache", input = "text", level = "chars", order = 8,
      windows = { base = 256, factor = 4, top = 65536 } },
    { name = "word_kn", kind = "kn", input = "text", level = "words", order = 6 },
    { name = "word_window", kind = "window", input = "text", level = "words",
      windows = { base = 256, factor = 4 }, bands = 3 },
    { name = "class_kn", kind = "kn", input = "text", level = "words", classes = ladder,
      order = { 3, 3, 3, 5, 5, 6 } },
    { name = "class_target_kn", kind = "kn", input = "text", level = "words", classes = ladder,
      target = "class", order = { 3, 3, 3, 5, 5, 7 } },
    { name = "history_tilt", kind = "tilt", input = "text", level = "words", condition = "history",
      half_lives = { base = 32, factor = 8 }, history_order = 3, order = 6 },
    { name = "sentences_tilt", kind = "tilt", input = "text", level = "words", condition = "sentences",
      order = 6, clusters = { 16 }, prior_order = { 1 } },
    { name = "class_tilt", kind = "tilt", input = "text", level = "words", condition = "history",
      half_lives = { base = 32, factor = 8 }, history_order = 3, classes = { 2 }, order = { 3 } },
  },
})
print("train bpc:", stats.train_bpc)
local bpc, r = m:score({ text = { text = text, lo = split, hi = #text } })
print("test bpc:", bpc, "accuracy:", r.acc)
print("ROMEO:" .. m:generate({ text = { text = "ROMEO:" }, n = 200, seed = 1 }))
m:destroy()
Illustrative: runs outside the browser.
Details
  • lo and hi bound the byte range to fit or score.
  • Every expert here names its input.
KindKeys
knlevel, order, optional classes and target
cachelevel = "chars", order, windows = { base, factor, top }
windowlevel = "words", windows = { base, factor }, bands
tiltlevel = "words", condition, order, optional classes
  • order is the expert's top n-gram order, a whole number of at least 1.
  • A cache takes its match order, a whole number from 0. Its windows run from base by factor up to top bytes.
  • A window's windows run from base by factor up to the train word count. bands, a whole count of at least 1, groups them into that many bands.
  • windows needs base at least 1 and factor above 1.
  • classes lists ascending word class counts, each from 2 to below the train vocabulary. order then lists one order per class count.
  • target = "class" goes with classes and predicts the next word's class.
  • A tilt's condition is "history" or "sentences".
  • A history tilt takes half_lives = { base, factor }, a ladder of half-lives in words, and history_order, a whole order of at least 1. Only a history tilt takes them.
  • A sentences tilt takes clusters, a list of cluster counts, and prior_order, one cluster chain order per count. Only a sentences tilt takes them.
  • words.boundary can span several bytes here, such as "\n\n" for a blank line.
  • score returns bits per byte and { acc, n }. stats.train_bpc is the train loss in bits.
  • predict returns an ivec of predicted next bytes.
  • m:generate({ [input] = { text = prompt }, n, seed }) returns n sampled bytes after the prompt. The same seed gives the same text.
  • A prompt byte outside the model's byte map raises.

Tokenizer

Raw n-gram hashing

tokenizer.tokenize_raw hashes text straight to sparse n-gram count features in one shot. It fits no vocabulary, and the same n-gram gets a stable column id across documents.

local tokenizer = require("santoku.learn.tokenizer")
local X = tokenizer.tokenize_raw({
  texts = { "hello", "hello world" },
  ngram_min = 3,
  ngram_max = 3,
  normalize = true,
})
local off = X:offsets()
print("docs:", off:size() - 1)
print("ngrams in doc 1:", off:get(1) - off:get(0))
print("ngrams in doc 2:", off:get(2) - off:get(1))
print("total ngram count:", X:values():sum())
local tok2 = tokenizer.tokenize_raw({ texts = { "abc", "abc" }, ngram_min = 3, ngram_max = 3 }):neighbors()
print("shared column id:", tok2:get(0) == tok2:get(1))
local X3 = tokenizer.tokenize_raw({ texts = { "ababab" }, ngram_min = 2, ngram_max = 2 })
print("distinct bigrams:", X3:neighbors():size())
print("most frequent count:", (X3:values():max()))
local framed = tokenizer.tokenize_raw({ texts = { "a" }, ngram_min = 3, ngram_max = 3, terminals = true })
print("trigrams of a with terminals:", framed:neighbors():size())
print(require("santoku.error").pcall(tokenizer.tokenize_raw, { texts = { "x" }, ngram_max = 1, terminal = true }))
return X:neighbors():size()
Details
  • tokenize_raw returns a csr with one row per text. Its neighbors are the ids and its values f32 counts.
  • level defaults to "chars", byte n-grams. The Hashed word n-grams card covers "words".
  • terminals = true wraps each text in bytes 0x01 and 0x02. The ids then equal the gram keys that a chars tokenizer with terminals = true fits.
  • At the words level, terminals = true adds start and end symbols the same way.
  • tokenize_raw takes texts, ngram_min, ngram_max, normalize, level and terminals. Any other key raises.

Hashed word n-grams

tokenize_raw with level = "words" splits each text into words and hashes word n-grams over ngram_min..ngram_max. The values are counts, and there's no vocabulary.

local tokenizer = require("santoku.learn.tokenizer")
local err = require("santoku.error")
local function words (texts, nmax)
  return tokenizer.tokenize_raw({ texts = texts, level = "words", ngram_min = 1, ngram_max = nmax or 1,
    normalize = true })
end
local X = words({ "the cat, the hat" })
print("distinct words:", X:neighbors():size(), "total:", X:values():sum())
print("e-book is e book:", words({ "e-book" }):neighbors():eq(words({ "e book" }):neighbors()))
print("isbn words:", words({ "9780306406157" }):neighbors():size(), words({ "978-0-306-40615-7" }):neighbors():size())
print("1-grams, 1-2 grams:", words({ "a b c" }):neighbors():size(), words({ "a b c" }, 2):neighbors():size())
print("folded:", words({ "Pérez" }):neighbors():eq(words({ "perez" }):neighbors()))
print(err.pcall(tokenizer.tokenize_raw, { texts = { "x" }, ngram_max = 1, level = "flat" }))
return X:neighbors():size()
Details
  • A word is a run of letters and digits, Unicode ones included. Combining marks continue a word.
  • Everything else separates. So e-book gives e and book, a bare ISBN stays one word, and a hyphenated ISBN splits.
  • Ids sit in [2^59, 2^60) and are sorted within each row.
  • Keep the ids in the ivec and compare them there. A Lua number holds 53 bits, and a wasm32 build truncates.
  • Any other level raises "tokenize_raw: level must be chars|words".

Fitted vocabularies

tok:fit builds a vocabulary on training text, and tok:tokenize maps new text onto the fitted vocabulary. Unseen n-grams don't grow the vocabulary, so train and serve agree on columns.

local tokenizer = require("santoku.learn.tokenizer")
local tok = tokenizer.create({ ngram_min = 3, ngram_max = 3, normalize = true })
local X = tok:fit({ texts = { "hello", "world" } })
print("training rows, vocab:", X:shape())
print("nnz:", X:nnz())
local X2 = tok:tokenize({ texts = { "brand new text" } })
print("new rows, vocab:", X2:shape())
return select(2, X:shape())
Details
  • tokenizer.create takes ngram_min, ngram_max, level, normalize and terminals. Any other key raises.
  • fit and tokenize return a csr with one row per text. Its column count is the vocabulary size.
  • tokenize before fit raises "tokenizer: tokenize before fit".

Regex extraction to spans

tokenizer.spans(texts, prog) runs a compiled regex program over a batch of texts. It returns a spans set with one span document per text and s and e columns.

local tokenizer = require("santoku.learn.tokenizer")
local re = require("santoku.re")
local arr = require("santoku.array")
local texts = { "The quick brown fox", "jumps over 42 dogs" }
local T = tokenizer.spans(texts, re.prog("[A-Za-z0-9]+"))
local off, s, e = T:offsets(), T:col("s"), T:col("e")
for d = 1, 2 do
  local words = {}
  for j = off:get(d - 1), off:get(d) - 1 do
    words[#words + 1] = texts[d]:sub(s:get(j) + 1, e:get(j))
  end
  print("doc " .. d .. ":", arr.concat(words, "|"))
end
local W = tokenizer.spans(texts, tokenizer.WORDS)
print("same starts as WORDS:", W:col("s"):eq(s))
return s:size()
Details
  • tokenizer.WORDS is the compiled "[A-Za-z0-9]+" program, and tokenizer.WORDS_PATTERN its source.
  • A pattern that fails to match cleanly raises "extract: pattern match failed (re status N)" instead of dropping tokens.

Shape-tagged tokens

A pattern with named groups tags each token, and tokenizer.spans adds a ty column of tag ids. tokenizer.SHAPES tags word shapes and punctuation runs.

local tokenizer = require("santoku.learn.tokenizer")
local arr = require("santoku.array")
local text = "IBM bought 42 Apples in 1996."
local S = tokenizer.spans({ text }, tokenizer.SHAPES)
local out = {}
for j = 0, S:n() - 1 do
  local s, e = S:col("s"):get(j), S:col("e"):get(j)
  out[#out + 1] = text:sub(s + 1, e) .. "=" .. S:col("ty"):get(j)
end
print(arr.concat(out, " "))
return S:n()
Details
  • The shapes include caps, cap, low, d4, num and punct.

Word n-grams over tokens

Feed extracted word spans into a words-level tokenizer, and its n-grams range over the word sequence instead of raw bytes.

local tokenizer = require("santoku.learn.tokenizer")
local err = require("santoku.error")
local texts = { "the quick brown fox", "the lazy dog sleeps" }
local T = tokenizer.spans(texts, tokenizer.WORDS)
local w = tokenizer.create({ ngram_min = 1, ngram_max = 2, level = "words" })
local X = w:fit({ texts = texts, tokens = T })
print("rows, word ngram vocab:", X:shape())
local Y = w:tokenize({ texts = texts, tokens = T })
print("tokenize equals fit:", X:eq(Y))
print(err.pcall(tokenizer.create, { ngram_max = 2, level = "words", terminals = true }))
return select(2, X:shape())
Details
  • A words-level tokenizer needs tokens spans with s and e columns at fit and tokenize.
  • The words level takes no normalize or terminals. Normalize the texts first, as the Text normalization card shows.
  • A chars-level tokenizer raises on tokens spans.
  • tokenize against the fitted vocabulary reproduces the fit exactly.

Text normalization

tokenizer.normalize(texts) returns new strings, lowercased, with accents folded and whitespace collapsed. Normalize first, extract word spans from the normalized strings, and fit on those same strings.

local tokenizer = require("santoku.learn.tokenizer")
local arr = require("santoku.array")
local norm = tokenizer.normalize({ "Café  NOIR", "cafe noir" })
print("normalized:", norm[1], norm[2])
print("folded:", arr.concat(tokenizer.normalize({ "Straße", "Œuvre", "Москва", "Ελλάδα", "Єва" }), " "))
local T = tokenizer.spans(norm, tokenizer.WORDS)
local w = tokenizer.create({ ngram_min = 1, ngram_max = 2, level = "words" })
local X = w:fit({ texts = norm, tokens = T })
print("word ngram vocab:", select(2, X:shape()))
return select(2, X:shape())
Details
  • The fold covers Latin, IPA, Greek and Cyrillic.
  • Every letter lowercases.
  • Russian and Greek transliterate, so Москва gives moskva.
  • æ and œ expand to ae and oe, and ß gives s.
  • Other letters lose their marks to the base letter.
  • Letters with no ASCII base stay lowercase, so Ukrainian є and Serbian ђ stay Cyrillic.
  • ASCII letters only lowercase.
  • The normalize = true options of a chars tokenizer, tokenize_raw and aho use the same fold.
  • Word spans index into the text they were extracted from. So the spans and the fit must use the same normalized strings.
  • Accented and plain spellings then share columns.

Aho-Corasick matching

Multi-pattern matching

aho.create builds an Aho-Corasick automaton over the patterns. predict finds every pattern in one pass over the text and returns a spans set with id, start and end columns.

local aho = require("santoku.learn.aho")
local ac = aho.create({ patterns = { "foo", "bar", "baz" } })
local text = "foo bar baz"
local S = ac:predict({ texts = { text } })
local ids, starts, ends = S:col("id"), S:col("s"), S:col("e")
print("matches:", ids:size())
for i = 0, ids:size() - 1 do
  local s, e = starts:get(i), ends:get(i)
  print(text:sub(s + 1, e), "pattern " .. ids:get(i), s, e)
end
return ids:size()

Formatted tag output

ac:tag rewrites matches through a format string. %match and %id give the raw hit, and %name gives the display name.

local aho = require("santoku.learn.aho")
local ac = aho.create({ patterns = { "foo", "bar" } })
print(ac:tag({ texts = { "foo and bar" }, fmt = "[%match:%id]" })[1])
local cities = aho.create({
  patterns = { "nyc", "la" },
  names = { "New York City", "Los Angeles" },
})
print(cities:tag({
  texts = { "visit nyc or la" },
  fmt = '<span title="%hname">%hmatch</span>',
})[1])
local amp = aho.create({ patterns = { "a&b" } })
print(amp:tag({ texts = { "see a&b here" }, fmt = "<b>%hmatch</b>" })[1])
return true
Details
  • %hmatch and %hname are HTML-escaped variants, safe to inject into markup.

Unicode normalization

With normalize = true, matching folds case and strips diacritics on both sides. Spans and tag output keep the original bytes.

local aho = require("santoku.learn.aho")
local ac = aho.create({ patterns = { "cafe" }, normalize = true })
print(ac:tag({ texts = { "at café now" }, fmt = "[%match]" })[1])
local up = aho.create({ patterns = { "hello" }, normalize = true })
print(up:tag({ texts = { "say HELLO there" }, fmt = "[%match]" })[1])
local S = ac:predict({ texts = { "café" } })
print("byte span:", S:col("s"):get(0), S:col("e"):get(0))
return S:col("id"):size()
Details
  • cafe finds café, and hello finds HELLO.
  • The fold is tokenizer.normalize's, which the Text normalization card describes.

Longest match and token alignment

longest = true keeps only the longest overlapping hit. A tokens spans set restricts matches to token boundaries, so cat stops matching inside concatenate.

local aho = require("santoku.learn.aho")
local spans = require("santoku.spans")
local ivec = require("santoku.ivec")
local ny = aho.create({ patterns = { "new", "new york" }, names = { "New", "New York" } })
local S = ny:predict({ texts = { "new york city" } })
print("all matches:", S:col("id"):size())
S = ny:predict({ texts = { "new york city" }, longest = true })
print("longest only:", S:col("id"):size())
print(ny:tag({ texts = { "new york city" }, fmt = "[%name]", longest = true })[1])
local cat = aho.create({ patterns = { "cat" } })
local T = spans.create({ offsets = ivec.create({ 0, 3 }),
  s = ivec.create({ 0, 4, 16 }), e = ivec.create({ 3, 15, 19 }) })
local S2 = cat:predict({ texts = { "cat concatenate cat" } })
print("raw matches:", S2:col("id"):size())
S2 = cat:predict({ texts = { "cat concatenate cat" }, tokens = T })
print("token aligned:", S2:col("id"):size())
return S2:col("id"):size()

Excluded regions

Pass byte ranges as a pvec in exclude to mask regions out of matching. A second return reports, per region, whether the automaton recognized the excluded text.

local aho = require("santoku.learn.aho")
local pvec = require("santoku.pvec")
local ac = aho.create({ patterns = { "foo", "bar", "baz" } })
local exc = pvec.create()
exc:push(0, 3)
local S = ac:predict({ texts = { "foo bar baz" }, exclude = exc })
print("surviving ids:", S:col("id"):get(0), S:col("id"):get(1))
print(ac:tag({ texts = { "foo bar baz" }, fmt = "[%match]", exclude = exc })[1])
local ac2 = aho.create({ patterns = { "foo" } })
local exc2 = pvec.create()
exc2:push(0, 3)
exc2:push(4, 11)
local S2, hits = ac2:predict({ texts = { "foo hello world" }, exclude = exc2 })
print("matches:", S2:col("id"):size())
print("region recognized:", hits:get(0), hits:get(1))
return hits:size()
Details
  • A suggester uses that second return to skip already-linked entities.

Gazetteers

Large gazetteer automata

aho.create builds the goto table in a spill store, so a large gazetteer's table sits in a file-backed buffer. ac:persist writes the automaton, and aho.load maps it back for serving.

local aho = require("santoku.learn.aho")
local ivec = require("santoku.ivec")
local ac = aho.create({
  patterns = { "jane doe", "acme press", "acme" },
  names = { "Jane Doe", "Acme Press", "Acme Press" },
  priorities = ivec.create({ 2, 2, 1 }),
  normalize = true,
})
ac:persist("suggest.aho")
local served = aho.load("suggest.aho")
local S = served:predict({ texts = { "signed with acme press" }, longest = true })
return S:col("id"):size()
Illustrative: runs outside the browser.
Details
  • aho.create takes patterns, names, priorities and normalize.
  • ac:persist(path) writes path and the goto table to path .. ".goto".
  • aho.load(path) reads both files.

Typed gazetteers from gold spans

gaz.create({ texts, gold, n_types }) keys each gold span's raw bytes, counts its types, and builds an aho automaton over the keys.

local ds = require("santoku.learn.dataset")
local gaz = require("santoku.learn.gaz")
local tokenizer = require("santoku.learn.tokenizer")
local re = require("santoku.re")
local mtx = require("santoku.mtx")
local train, _, test_set = ds.read_conll2003("test/res/conll2003")
local gz = gaz.create({ texts = train.texts, gold = train.gold, n_types = 4 })
local words = tokenizer.spans(test_set.texts, re.prog("[^ ]+"))
local M, ids = gz:match(test_set.texts, { units = words })
print("matches:", M:n())
local out = mtx.create({ n_rows = 1, n_cols = 1, type = "f32" })
gz:tags({ words = words, matches = M, ids = ids, out = out })
print("words, tag columns:", out:shape())
gz:persist("conll.gaz")
local back = gaz.load("conll.gaz")
local M2 = back:match(test_set.texts, { units = words })
print("reloaded matches:", M2:n())
return M:n()
Illustrative: runs outside the browser.
Details
  • gz:match(texts, { units }) finds the longest surface matches aligned to the unit spans.
  • gz:match returns spans { s, e, ty } plus an ivec of entry ids. ty is the most frequent gold type of the surface, and ties go to the lowest.
  • gz:tags({ words, matches, ids, out }) fills out, an f32 mtx, with one row per word and 1 + 2 x n_types columns: O, then B and I per type.
  • Each row splits the entry's type counts over B and I. A word outside every match is O.
  • The span tagger's gaz expert and segment chain call match and tags on the gaz object in its input.
  • gz:persist(path) writes the gazetteer, and gaz.load(path) reads it back.
  • gz:id() returns the key count and a 16-digit hex hash of the keys and type counts. A reloaded gazetteer returns the same id.
  • gaz.load raises "load: not a gazetteer file of this version (refit required)" on another format version.

Retrieval

Reranking with dense codes

retrieval.create({ doc_codes, ids }) builds a reranker for bm25 candidates. Each candidate's score blends its normalized lexical score with the dot product of the query and document codes.

local retrieval = require("santoku.learn.retrieval")
local csr = require("santoku.csr")
local mtx = require("santoku.mtx")
local ivec = require("santoku.ivec")
local fvec = require("santoku.fvec")
local dvec = require("santoku.dvec")
local arr = require("santoku.array")
local R = csr.create({
  offsets = ivec.create({ 0, 3 }),
  neighbors = ivec.create({ 0, 1, 2 }),
  values = fvec.create({ 1, 3, 2 }),
  n_cols = 3,
})
local D = mtx.create({ data = fvec.create({ 1, 0, 0, 1 }), n_rows = 2, n_cols = 2 })
local Qc = mtx.create({ data = fvec.create({ 1, 0 }), n_rows = 1, n_cols = 2 })
local r = retrieval.create({ doc_codes = D })
local F, pos = r:rerank({ candidates = R, queries = Qc, weights = dvec.create({ 0.04, 0.96 }) })
print("order:", arr.concat(F:neighbors():table(), " "))
print("input positions:", arr.concat(pos:table(), " "))
return F:nnz()
Illustrative: runs outside the browser.
Details
  • doc_codes is an f32 or f64 mtx of document codes, held zero-copy.
  • Without ids, a candidate id is its row in doc_codes. A duplicate id raises.
  • r:rerank({ candidates, queries, weights, extra, norms }) keeps the candidate set and reorders it. extra and norms are optional.
  • candidates is a csr whose values hold the bm25 scores, such as csr:bm25 plus csr:topk or santoku.sqlite.fts give.
  • queries is an mtx of query codes with the type and n_cols of doc_codes.
  • weights is a dvec, lexical first: { w_lex, w_dense, w_X1, ... }, with 2 plus extra's column count entries.
  • rerank divides each row's lexical scores by the row's max, or by norms when given. norms holds one positive value per candidate row.
  • rerank adds w_dense times the dot product of the query and document codes.
  • rerank adds w_Xj times column j of extra, an f64 mtx with one row per candidate entry.
  • rerank returns a new csr and an ivec of each output entry's position in the input. Ties go to the lower id.
  • A candidate with no row in doc_codes keeps its lexical term.
  • dvec.create({ 1 - alpha, alpha }) gives an alpha blend, and { 1, 0 } keeps the lexical order.
  • The learn-llama page reranks scifact with gguf embeddings as the codes.

Upgrading

Changes in 22

santoku-learn 22 changes pool.fit's expert options and every persisted format. Models from 21 don't load, so refit them.

local pool = require("santoku.learn.pool")
local err = require("santoku.error")
print(err.pcall(pool.fit, {
  inputs = { text = { text = "ab ab ab" } },
  groups = {},
  experts = { { name = "kn", kind = "kn", input = "text", level = "chars", order = 3 } },
}))
Illustrative: runs outside the browser.
Details
Head2122
allpool.fit views = { units, boundary }words = { pattern, boundary }
allscore(inputs, { expected })score(inputs, { targets })
alla head ignored n_types, views, groups or stack it doesn't takeraises
allinput on every expertno input on cnb, vote, geo, fc, stack and segment
allclasses = true, a number or { base, factor }classes lists the class counts
docspool.fit stack = { input, n_types, experts }candidates = { input, n_types, experts }, with no groups
docsstats.stack on a candidates fitstats.candidates
docskind propagate, with k and csremoved
docsbns binaryremoved
docsbns max_order optionalorder required
docsfc k and max_trees, from lists several bns expertsbins and trees required, from names one
docsstack max_treestrees
docsscore returned every expert's picksonly with experts = true
docs, denseforest max_trees grows to an out-of-bag plateau, and shifttrees grows exactly trees trees; shift removed
docs, densedense input group_offsetsforest columns = "each"
tagskn order fittedorder = { forward, reverse } required
tagssided and windowed gaz radius fittedradius required on sided, optional on gaz
tagsgaz window = trueremoved; a radius gives the window
textkn and tilt order fittedorder required
textchars cache order fitted, fixed windowsorder and windows required
textwords cachekind window, with windows and bands required
texthistory tilt with fixed half-liveshalf_lives and history_order required
textsentences tilt with 16 clustersclusters and prior_order required
  • 22 adds the geo kind, salience on cnb, vote and geo, the stack kind in the tags head, forest patch, and dataset.read_eurlex57k's fields argument.
  • From 20, 21 replaced santoku.learn.krr with santoku.learn.pool. krr, features, spectral, ridge, decide, class_stats, cands, ner, lm, evaluator and util are gone.
  • 21 moved booleanizer under santoku.learn.pool, which is internal. dataset.read_adult still runs it.
  • 21's tokenize_raw returns one csr and takes level in place of mode, with no n_samples. tokenizer.create takes level too.
  • 21's aho.create replaces aho.prepare and builder:build. retrieval.create replaces retrieval.reranker, and rerank takes one options table.

Examples

Projects that toku init creates with this rock. The examples page shows their files.

  • A text classifier: A command that trains a kernel ridge text classifier on a small built-in dataset and labels new text. toku init --example classify my-classify
  • A full-text search command: A command that indexes notes in a sqlite file and ranks them for a query with BM25. toku init --example search my-search