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-matrix

View on LuaRocks

typed numeric vectors, dense, sparse and bit matrices, and top-k retrieval in C, under santoku search and ML

santoku-matrix is the numeric data layer of the framework: typed C-backed vectors, dense matrices (mtx), sparse matrices (csr), labelled span sets (spans), disk-backed mmap vectors, and C-level hash maps. It sits under santoku-learn and santoku.sqlite.fts. The vector and matrix modules run live in your browser.

Details
  • The vectors are ivec for i64, dvec for f64, fvec for f32 and svec for i32, plus pair and byte vectors.
  • Storage is zero-copy. create adopts the vectors you pass, so a change on one side is visible from the other.
  • In-place operations return self, so they chain.
  • Indices are 0-based throughout.
  • Feature transforms follow a fit/apply idiom. fit returns the learned weights, and you pass them back to apply.
  • Gather operations accept an out= destination to avoid allocation in hot loops.
  • On native builds the dense math routes through BLAS. Under WebAssembly the same functions compile to portable C loops, and this page ships that wasm build.
  • The live modules are ivec, dvec, fvec, pvec, mtx, csr and spans. Only the file-backed paths (persist, mmap) and the hash map modules are shown for reading.

Vectors

Typed vector basics

Vectors are growable typed arrays with 0-based indices. Sorting is in place, table converts to a plain Lua table, and every range argument is a half-open [start, end) pair.

local ivec = require("santoku.ivec")
local arr = require("santoku.array")
local err = require("santoku.error")
local v = ivec.create({ 5, 2, 8, 1, 9 })
local c = v:clone()
c:set(0, 50)
print("clone is independent:", v:get(0), c:get(0))
v:push(4)
print("size:", v:size())
print("sum:", v:sum())
local val, idx = v:max()
print("max:", val, "at index", idx)
v:asc()
print("sorted:", arr.concat(v:table(), " "))
print("head:", arr.concat(v:table(0, 3), " "))
v:insert(0, 0)
print("inserted:", arr.concat(v:table(), " "))
print("find(8):", v:find(8))
print(err.pcall(v.get, v, 99))
print(err.pcall(v.table, v, 2, 1))
local g = ivec.create({ 1, 2 })
g:set(4, 9)
print("set past the end grows:", g:size(), g:get(4))
return v:size()
Details
  • max and min return both the value and its index.
  • find returns the index of the first match, or nil.
  • clone returns an independent copy, as csr:clone does for sparse matrices.
  • Since santoku-matrix 6.0.0, an index, id or range outside the vector raises. The error names the function, the value and the valid range.
  • A range must satisfy 0 <= start <= end <= n.
  • set is the exception. set(i, x) past the end grows the vector to i + 1, and the slots it skips hold unspecified values.
  • An mmap-backed vector can't grow, so set past its end raises.
  • C extensions get the same checks from the santoku/bounds.h header.

Elementwise math

The float vectors carry the math: dot products, L2 magnitude, vector add and scalar scale (both in place), elementwise pow, exp and log, and rounding that chains into an integer conversion.

local dvec = require("santoku.dvec")
local arr = require("santoku.array")
local a = dvec.create({ 1, 2, 3 })
local b = dvec.create({ 4, 5, 6 })
print("dot:", a:dot(b))
print("magnitude:", dvec.create({ 3, 4 }):magnitude())
a:addv(b)
a:scale(2)
print("addv then scale:", arr.concat(a:table(), " "))
local p = dvec.create({ 1, 2, 3 })
p:pow(2)
print("pow:", arr.concat(p:table(), " "))
local r = dvec.create({ 1.4, 2.5, 3.6 })
local i = r:round():to_ivec()
print("round to_ivec:", arr.concat(i:table(), " "))
local e = dvec.create({ 0, 1, 2 })
e:exp()
e:log()
print("exp log roundtrip:", arr.concat(e:table(), " "))
return a:sum()
Details
  • round goes half away from zero, so 2.5 becomes 3.
  • dot, scale and addv are BLAS calls natively and plain loops in this wasm build.

Selection, gather and counting

where returns the indices where a comparison holds (gt, lt, ge, le, eq, ne). copy with an index vector gathers those positions into a new vector.

local ivec = require("santoku.ivec")
local dvec = require("santoku.dvec")
local arr = require("santoku.array")
local v = ivec.create({ 5, 0, 7, 0, 3 })
local idx = v:where("gt", 0)
print("hits:", arr.concat(idx:table(), " "))
local picked = ivec.create(idx:size())
picked:copy(v, idx)
print("picked:", arr.concat(picked:table(), " "))
local ids = ivec.create({ 2, 0, 1, 2 })
ids:lookup(ivec.create({ 100, 200, 300 }))
print("lookup:", arr.concat(ids:table(), " "))
local seg = ivec.create(5)
seg:zero()
seg:fill_segments(ivec.create({ 0, 2, 5 }), ivec.create({ 7, 9 }))
print("segments:", arr.concat(seg:table(), " "))
local bins = ivec.create({ 0, 2, 2, 1, 2 }):bincount(3)
print("bincount:", arr.concat(bins:table(), " "))
local wb = ivec.create({ 0, 2, 2, 1, 2 })
  :bincount(3, dvec.create({ 1, 0.5, 0.5, 2, 1 }))
print("weighted:", arr.concat(wb:table(), " "))
print("quantile bins:", arr.concat(ivec.create({ 5, 5, 5, 1 }):quantile_bins(4):table(), " "))
return picked:size()
Details
  • copy(src, idx, true) scatters into existing slots. It raises on an index past the destination instead of growing it.
  • lookup rewrites each element by using it as an index into a source vector. It keeps the vector's length, and raises on an index outside the source.
  • fill_segments broadcasts one value per csr-style segment.
  • bincount histograms small integer ids, optionally weighted by a dvec.
  • quantile_bins(bins) puts each value x in floor(bins * #{y < x} / n), so equal values share a bin.

Sorted ivecs as integer sets

A sorted ivec doubles as an integer set: jaccard, overlap, dice and tversky similarities, plus materialized intersection and union.

local ivec = require("santoku.ivec")
local arr = require("santoku.array")
local a = ivec.create({ 1, 2, 3, 4 })
local b = ivec.create({ 3, 4, 5, 6 })
print("jaccard:", a:set_jaccard(b))
print("overlap:", a:set_overlap(b))
print("dice:", a:set_dice(b))
print("intersect:", arr.concat(a:set_intersect(b):table(), " "))
print("union:", arr.concat(a:set_union(b):table(), " "))
local s = ivec.create({ 10, 20, 30, 40, 50 })
print("set_find(30):", s:set_find(30))
print("set_find(25):", s:set_find(25))
local t = ivec.create({ 10, 30, 50 })
t:set_insert(1, 20)
print("set_insert:", arr.concat(t:table(), " "))
return a:set_overlap(b)
Details
  • set_find is a binary search. It returns the position on a hit, and an encoded negative insertion point on a miss.
  • set_find pairs with set_insert to keep the vector sorted.

Bounded top-k heaps

pvec stores (i64, i64) pairs and compares on the second field. hmax(id, value, k) maintains a max-heap capped at k entries that retains the k smallest values.

local pvec = require("santoku.pvec")
local ivec = require("santoku.ivec")
local arr = require("santoku.array")
local heap = pvec.create()
heap:hmax(1, 50, 3)
heap:hmax(2, 10, 3)
heap:hmax(3, 30, 3)
heap:hmax(4, 40, 3)
heap:hmax(5, 20, 3)
print("kept:", heap:size())
heap:asc()
print("ids:", arr.concat(heap:keys():table(), " "))
print("values:", arr.concat(heap:values():table(), " "))
local i, p = heap:get(0)
print("best:", i, p)
local tied = pvec.from(ivec.create({ 4, 2, 7, 1 }), ivec.create({ 5, 5, 9, 5 }))
tied:asc()
print("ties by id:", arr.concat(tied:keys():table(), " "))
local grown = pvec.create()
grown:set(2, 7, 70)
print("set grows:", grown:size(), grown:get(2))
return heap:size()
Details
  • hmin retains the k largest values.
  • hmax and hmin are the streaming keep-the-best-k pattern used in retrieval.
  • asc then sorts the survivors, and keys and values split the pairs into ivecs.
  • rvec is the (i64, f64) twin for float scores.
  • Sorts and heaps on pvec and rvec break a value tie by the lower id.
  • get raises past the end. set(i, id, value) past the end grows the size to i + 1.
  • pvec.from(ids, values) builds pairs from two parallel ivecs, and rvec.from takes a dvec of values. Both raise when the lengths differ.

Dense matrices

Zero-copy matrix views

A dense matrix is a row-major view over a typed vector. Wrapping adopts the vector: data returns the very same object, and writes through either side are visible in the other.

local mtx = require("santoku.mtx")
local csr = require("santoku.csr")
local dvec = require("santoku.dvec")
local ivec = require("santoku.ivec")
local arr = require("santoku.array")
local v = dvec.create({ 1, 2, 3, 4, 5, 6 })
local M = mtx.create({ data = v, n_rows = 2, n_cols = 3 })
print("shape:", M:shape())
print("type:", M:type())
print("get(1, 2):", M:get(1, 2))
v:set(5, 60)
print("after vec set:", M:get(1, 2))
print("same object:", M:data() == v)
local Z = mtx.create({ n_rows = 2, n_cols = 2, type = "f64" })
print("zeroed:", Z:get(0, 0), Z:get(1, 1))
local I = mtx.create({ data = ivec.create({ 1, 2, 3, 4 }), n_rows = 2, n_cols = 2 })
print("inferred:", I:type())
local P = csr.from_pairs(
  ivec.create({ 0, 0, 1, 2, 2, 2 }),
  ivec.create({ 0, 1, 1, 0, 0, 1 }), 3, 2)
print("offsets:", arr.concat(P:offsets():table(), " "))
print("neighbors:", arr.concat(P:neighbors():table(), " "))
print("values:", arr.concat(P:values():table(), " "))
return M:shape()
Details
  • On this page the shared storage is wasm linear memory.
  • Allocation without data gives a zeroed matrix.
  • The element type is inferred from the wrapped vector.
  • csr.from_pairs counts (row, col) index pairs into a sparse matrix, and a repeated pair adds up in its value.

Axis reductions

Every reduction takes an axis, "row" or "col", and returns a vector: sums, maxs, mins, mags (L2 norm per slice), maxargs and minargs (the winning index per slice), and argsort.

local mtx = require("santoku.mtx")
local dvec = require("santoku.dvec")
local arr = require("santoku.array")
local M = mtx.create({ data = dvec.create({ 1, 2, 3, 4, 5, 6 }), n_rows = 2, n_cols = 3 })
print("row sums:", arr.concat(M:sums("row"):table(), " "))
print("col sums:", arr.concat(M:sums("col"):table(), " "))
print("row maxs:", arr.concat(M:maxs("row"):table(), " "))
print("col mins:", arr.concat(M:mins("col"):table(), " "))
local A = mtx.create({ data = dvec.create({ 1, 5, 2, 9, 3, 7 }), n_rows = 2, n_cols = 3 })
print("row maxargs:", arr.concat(A:maxargs("row"):table(), " "))
local G = mtx.create({ data = dvec.create({ 3, 4, 0, 5, 12, 0 }), n_rows = 2, n_cols = 3 })
print("row mags:", arr.concat(G:mags("row"):table(), " "))
local S = mtx.create({ data = dvec.create({ 5, 1, 3, 9, 2, 7 }), n_rows = 2, n_cols = 3 })
print("argsort:", arr.concat(S:argsort("row", "asc"):table(), " "))
return M:shape()
Details

argsort returns per-slice orderings concatenated into one ivec.

Transpose, gather and hcat

transpose, rows and cols return new matrices, and row extracts one row as a vector. hcat concatenates columns in place and returns self.

local mtx = require("santoku.mtx")
local dvec = require("santoku.dvec")
local ivec = require("santoku.ivec")
local arr = require("santoku.array")
local M = mtx.create({ data = dvec.create({ 1, 2, 3, 4, 5, 6 }), n_rows = 2, n_cols = 3 })
local T = M:transpose()
print("T shape:", T:shape())
print("T data:", arr.concat(T:data():table(), " "))
local N = mtx.create({
  data = dvec.create({ 1, 2, 3, 4, 5, 6, 7, 8, 9 }),
  n_rows = 3, n_cols = 3,
})
print("rows(2, 0):", arr.concat(N:rows(ivec.create({ 2, 0 })):data():table(), " "))
print("cols(2, 1):", arr.concat(N:cols(ivec.create({ 2, 1 })):data():table(), " "))
print("row(1):", arr.concat(N:row(1):table(), " "))
local A = mtx.create({ data = dvec.create({ 1, 2, 5, 6 }), n_rows = 2, n_cols = 2 })
local B = mtx.create({ data = dvec.create({ 3, 7 }), n_rows = 2, n_cols = 1 })
print("hcat is self:", A:hcat(B) == A)
print("hcat data:", arr.concat(A:data():table(), " "))
local out = mtx.create({ n_rows = 1, n_cols = 1 })
print("out reused:", N:rows(ivec.create({ 1 }), out) == out)
return A:shape()
Details
  • rows gathers whole rows by index vector, in the order given.
  • Gathers accept an out= destination that is resized and reused. Hot loops rely on that pattern to avoid allocation.

Matrix products

multiply is a full matmul with optional transpose flags for either operand and an out= destination. multiplyv is the matrix-vector product, with a transpose flag that computes A transposed times v.

local mtx = require("santoku.mtx")
local dvec = require("santoku.dvec")
local arr = require("santoku.array")
local A = mtx.create({ data = dvec.create({ 1, 2, 3, 4 }), n_rows = 2, n_cols = 2 })
local B = mtx.create({ data = dvec.create({ 5, 6, 7, 8 }), n_rows = 2, n_cols = 2 })
local C = A:multiply(B)
print("A*B:", arr.concat(C:data():table(), " "))
local Ct = A:multiply(B, false, true)
print("A*Bt:", arr.concat(Ct:data():table(), " "))
local M = mtx.create({ data = dvec.create({ 1, 2, 3, 4, 5, 6 }), n_rows = 2, n_cols = 3 })
local y = M:multiplyv(dvec.create({ 1, 2, 3 }))
print("M*v:", arr.concat(y:table(), " "))
local yt = M:multiplyv(dvec.create({ 1, 2 }), true)
print("Mt*v:", arr.concat(yt:table(), " "))
local buf = dvec.create(0)
print("out reused:", M:multiplyv(dvec.create({ 1, 1, 1 }), false, buf) == buf)
return C:shape()
Details
  • Natively multiply and multiplyv are cblas_dgemm and cblas_dgemv.
  • In this wasm build they run as portable C loops, with the same results.

Symmetric eigendecomposition

w = M:eigh() decomposes a square f32 or f64 mtx in place and reads only its upper triangle. It overwrites M with the eigenvectors as columns and returns the eigenvalues in ascending order.

local mtx = require("santoku.mtx")
local dvec = require("santoku.dvec")
local A = mtx.create({ data = dvec.create({ 2, 1, 1, 2 }), n_rows = 2, n_cols = 2 })
local V = A:clone()
local w = V:eigh()
print("eigenvalues:", w:get(0), w:get(1))
print("first eigenvector:", V:get(0, 0), V:get(1, 0))
return w:size()
Illustrative: runs outside the browser.
Details
  • Column j of M pairs with w:get(j).
  • w is a new vector of M's element type: fvec for f32, dvec for f64.
  • eigh calls LAPACK's divide-and-conquer driver (ssyevd or dsyevd).
  • Clone M first to keep the input.
  • eigh raises on a type other than f32 or f64, a non-square matrix, n above INT_MAX, or a LAPACK failure ("eigh failed", "LAPACKE_dsyevd info <n>").
  • A NaN in the upper triangle raises with info -5 while LAPACKE's NaN check is on, which is the default.
  • The wasm build has no LAPACK, so M.eigh is nil there. Check if M.eigh then before you call it.

Fit and apply transforms

center subtracts per-column means and returns them. standardize scales each column to unit standard deviation without centering, and returns the weights.

local mtx = require("santoku.mtx")
local dvec = require("santoku.dvec")
local arr = require("santoku.array")
local M = mtx.create({ data = dvec.create({ 1, 10, 3, 20 }), n_rows = 2, n_cols = 2 })
local means = M:center()
print("means:", arr.concat(means:table(), " "))
print("centered:", arr.concat(M:data():table(), " "))
local N = mtx.create({ data = dvec.create({ 2, 15 }), n_rows = 1, n_cols = 2 })
N:center(means)
print("applied:", arr.concat(N:data():table(), " "))
local S = mtx.create({ data = dvec.create({ 1, 10, 3, 20 }), n_rows = 2, n_cols = 2 })
local w = S:standardize()
print("weights:", arr.concat(w:table(), " "))
local H = mtx.create({ data = dvec.create({ 2, 15 }), n_rows = 1, n_cols = 2 })
H:scale_cols(w)
print("held out:", arr.concat(H:data():table(), " "))
local L = mtx.create({ data = dvec.create({ 3, 4, 0, 0, 5, 12 }), n_rows = 2, n_cols = 3 })
L:normalize()
print("row mags:", arr.concat(L:mags("row"):table(), " "))
return w:size()
Details
  • Pass center's means back to center held-out data identically.
  • scale_cols applies standardize's weights to held-out rows.
  • standardize("rms") scales by root mean square instead.
  • normalize scales each row to unit L2 norm in place.
  • csr has standardize, scale_cols and normalize, and no center.

Sparse matrices

Sparse row construction

A csr is offsets (length n_rows plus one), neighbors (column ids), and optional values. Omit values and it's a binary matrix with type "none".

local csr = require("santoku.csr")
local ivec = require("santoku.ivec")
local arr = require("santoku.array")
local X = csr.create({
  offsets = ivec.create({ 0, 2, 3, 5 }),
  neighbors = ivec.create({ 0, 2, 1, 0, 3 }),
  n_cols = 4,
})
print("shape:", X:shape())
print("nnz:", X:nnz())
print("type:", X:type())
local inferred = csr.create({ offsets = ivec.create({ 0, 2 }), neighbors = ivec.create({ 3, 7 }) })
print("inferred n_cols:", select(2, inferred:shape()))
print(require("santoku.error").pcall(csr.create,
  { offsets = ivec.create({ 0, 1 }), neighbors = ivec.create({ -1 }) }))
local B = csr.create({ n_cols = 4, values = "f32" })
B:push(0, 1.5):push(2, 2.5):endrow()
B:endrow()
B:push(3):endrow()
print("offsets:", arr.concat(B:offsets():table(), " "))
print("neighbors:", arr.concat(B:neighbors():table(), " "))
print("value(1):", B:values():get(1))
local C = csr.from_classes(ivec.create({ 2, 0, 1, 2 }))
print("classes:", arr.concat(C:neighbors():table(), " "))
local M = csr.from_mask(ivec.create({ 1, 0, 1, 1, 0 }))
print("mask offsets:", arr.concat(M:offsets():table(), " "))
return X:nnz()
Details
  • Wrap existing vectors zero-copy, or build a csr incrementally.
  • push adds (column, value) pairs, and endrow closes each row, including empty ones.
  • from_classes turns one label per row into one-hot rows.
  • from_mask turns a 0/1 vector into a single indicator column.
  • Given offsets and no n_cols, create infers n_cols as the largest column id plus one.
  • A column id below 0, or at n_cols or beyond, raises.
  • csr has no hstack since santoku-matrix 6.0.0. Stack columns with cols and hcat.

Feature weighting

bm25 with no weights fits BM25 idf per column and the average row length, rewrites each value to its saturated BM25 weight, and returns both.

local csr = require("santoku.csr")
local ivec = require("santoku.ivec")
local fvec = require("santoku.fvec")
local X = csr.create({
  offsets = ivec.create({ 0, 1, 2, 4 }),
  neighbors = ivec.create({ 0, 0, 0, 1 }),
  values = fvec.create({ 1, 1, 1, 1 }),
  n_cols = 2,
})
local w, avgdl = X:bm25()
print("idf weights:", w:get(0), w:get(1))
print("average row length:", avgdl)
local Y = csr.create({
  offsets = ivec.create({ 0, 2 }),
  neighbors = ivec.create({ 0, 1 }),
  values = fvec.create({ 1, 1 }),
  n_cols = 2,
})
Y:bm25(w, avgdl)
print("applied:", Y:values():get(0), Y:values():get(1))
local N = csr.create({
  offsets = ivec.create({ 0, 2, 3 }),
  neighbors = ivec.create({ 0, 1, 1 }),
  n_cols = 2,
})
N:normalize()
print("materialized:", N:type())
print("values:", N:values():get(0), N:values():get(2))
N:scale_cols(fvec.create({ 10, 100 }))
print("scaled:", N:values():get(0), N:values():get(2))
return N:type()
Details
  • The idf is log((N - df + 0.5) / (df + 0.5)), floored at 1e-6.
  • k1 is 1.2 and b is 0.75 unless you pass them as bm25(k1, b).
  • Pass the idf and average back as bm25(w, avgdl) to weight held-out rows with the fitted statistics. Row lengths are measured per row.
  • normalize L2-scales each row, and materializes f32 values on a binary matrix.
  • scale_cols multiplies each column by a weight. It's the one way to apply fitted weights to held-out rows.
  • bns(labels) fits supervised per-column weights and returns them without touching the matrix. Apply them with scale_cols.
  • standardize fits scale weights, applies them, and returns them.

Gather, cols, hcat and transpose

rows gathers whole rows into a new csr. cols keeps a subset of columns and remaps their ids to a compact 0-based space.

local csr = require("santoku.csr")
local ivec = require("santoku.ivec")
local fvec = require("santoku.fvec")
local arr = require("santoku.array")
local X = csr.create({
  offsets = ivec.create({ 0, 2, 4, 6 }),
  neighbors = ivec.create({ 10, 20, 30, 40, 50, 60 }),
  values = fvec.create({ 1, 2, 3, 4, 5, 6 }),
  n_cols = 100,
})
local Y = X:rows(ivec.create({ 0, 2 }))
print("gathered:", arr.concat(Y:neighbors():table(), " "))
local S = csr.create({
  offsets = ivec.create({ 0, 3, 5 }),
  neighbors = ivec.create({ 0, 1, 2, 1, 3 }),
  values = fvec.create({ 1, 2, 3, 4, 5 }),
  n_cols = 4,
})
local P = S:cols(ivec.create({ 1, 3 }))
print("selected:", arr.concat(P:neighbors():table(), " "))
print("remapped shape:", P:shape())
local A = csr.create({
  offsets = ivec.create({ 0, 2, 3 }),
  neighbors = ivec.create({ 0, 1, 2 }),
  n_cols = 3,
})
local B = csr.create({
  offsets = ivec.create({ 0, 1, 2 }),
  neighbors = ivec.create({ 0, 1 }),
  n_cols = 2,
})
A:hcat(B)
print("hcat shifted:", arr.concat(A:neighbors():table(), " "))
local V = csr.create({
  offsets = ivec.create({ 0, 2, 3 }),
  neighbors = ivec.create({ 0, 1, 0 }),
  values = fvec.create({ 1, 2, 3 }),
  n_cols = 2,
})
local T = V:transpose()
print("T values:", T:values():get(0), T:values():get(1), T:values():get(2))
return A:shape()
Details
  • hcat concatenates feature blocks in place. It shifts the right block's column ids past the left block's width.
  • transpose flips rows and columns and carries values along.

Dense to sparse

mtx:to_sparse drops zeros, or anything whose magnitude is at most an optional epsilon, into a csr whose values keep the matrix's element type.

local mtx = require("santoku.mtx")
local dvec = require("santoku.dvec")
local arr = require("santoku.array")
local M = mtx.create({
  data = dvec.create({ 1, 0, 3, 0, 2, 0 }),
  n_rows = 2, n_cols = 3,
})
local X = M:to_sparse()
print("offsets:", arr.concat(X:offsets():table(), " "))
print("neighbors:", arr.concat(X:neighbors():table(), " "))
print("value(1):", X:values():get(1))
return X:nnz()

Retrieval and evaluation

Brute-force top-k retrieval

corpus:topk(queries, k) scores every corpus row against every query row by dot product, and keeps each query's k best with a bounded heap.

local mtx = require("santoku.mtx")
local dvec = require("santoku.dvec")
local arr = require("santoku.array")
local corpus = mtx.create({
  data = dvec.create({ 1, 0, 0, 1, 0.5, 0.5 }),
  n_rows = 3, n_cols = 2,
})
local q = mtx.create({
  data = dvec.create({ 1, 0 }),
  n_rows = 1, n_cols = 2,
})
local P = corpus:topk(q, 2)
print("shape:", P:shape())
print("nnz:", P:nnz())
print("offsets:", arr.concat(P:offsets():table(), " "))
print("ids:", arr.concat(P:neighbors():table(), " "))
print("scores:", arr.concat(P:values():table(), " "))
return P:nnz()
Details
  • The dot products are BLAS calls natively and C loops here.
  • The result is a csr with one row per query. neighbors hold corpus row ids and values hold scores, both ordered by descending score.

Sparse top-k retrieval

docs:topk(Q, k) scores every query row against every document row by sparse dot product, and keeps each query's k best.

local csr = require("santoku.csr")
local ivec = require("santoku.ivec")
local fvec = require("santoku.fvec")
local arr = require("santoku.array")
local docs = csr.create({
  offsets = ivec.create({ 0, 2, 3, 4 }),
  neighbors = ivec.create({ 0, 1, 1, 0 }),
  values = fvec.create({ 1, 2, 1, 3 }),
  n_cols = 2,
})
local Q = csr.create({
  offsets = ivec.create({ 0, 1, 2 }),
  neighbors = ivec.create({ 0, 1 }),
  values = fvec.create({ 1, 2 }),
  n_cols = 2,
})
local P = docs:topk(Q, 2)
print("offsets:", arr.concat(P:offsets():table(), " "))
print("ids:", arr.concat(P:neighbors():table(), " "))
print("scores:", arr.concat(P:values():table(), " "))
return P:nnz()
Details
  • csr:topk builds a term-to-document index from the document csr once, so a query only visits documents that share a term with it.
  • The result has one row per query. neighbors hold document row ids and values hold scores, best first.
  • The result's n_cols is the document count.
  • Weight the documents with bm25 and pass query term weights as the query values to rank the way BM25 does.

Paired significance test

a:paired_test(b, iters, seed) takes two systems' per-row scores, and returns the mean of b - a and a two-sided sign-flip p-value.

local dvec = require("santoku.dvec")
local a = dvec.create({ 0.5, 0.6, 0.2, 0.9, 0.4 })
local b = dvec.create({ 0.7, 0.6, 0.5, 0.95, 0.6 })
local delta, p = a:paired_test(b, 1000, 1)
print("delta:", delta, "p:", p)
return delta
Details
  • The per-query dvec that santoku.learn.evaluator.ndcg returns holds such scores.
  • iters defaults to 10000 and seed to 1.
  • paired_test seeds its own generator, so the same seed gives the same p.

Folds, spreads and rarest labels

v:fold_assign(K[, order]) reads v as one class per row and deals each class's rows round-robin over K folds. It returns a new ivec.

local ivec = require("santoku.ivec")
local csr = require("santoku.csr")
local arr = require("santoku.array")
local cls = ivec.create({ 3, 1, 3, 1, 3, 3 })
print("folds:", arr.concat(cls:fold_assign(2):table(), " "))
local order = ivec.create({ 5, 4, 3, 2, 1, 0 })
print("folds, reversed:", arr.concat(cls:fold_assign(2, order):table(), " "))
local part = ivec.create({ 0, 0, 0, 0 }):fold_assign(2, ivec.create({ 3, 1 }))
print("rows outside order:", arr.concat(part:table(), " "))
local off = ivec.create({ 0, 2, 2, 7, 12 })
print("diff:", arr.concat(off:diff():table(), " "))
print("clamp:", arr.concat(off:diff():clamp(0, 4):table(), " "))
print("spread(10, 4):", arr.concat(ivec.spread(10, 4):table(), " "))
print("spread(3, 5):", arr.concat(ivec.spread(3, 5):table(), " "))
local Y = csr.create({
  offsets = ivec.create({ 0, 2, 3, 3, 6 }),
  neighbors = ivec.create({ 0, 2, 0, 2, 1, 0 }),
  n_cols = 3,
})
print("rarest:", arr.concat(Y:rarest_label():table(), " "))
return off:diff():size()
Details
  • fold_assign deals in row order, or in the given order. Rows the order leaves out get -1.
  • diff returns the consecutive differences.
  • clamp(lo, hi) clamps in place and returns v.
  • ivec.spread(n, m) returns up to m evenly spaced indices in [0, n), so it holds min(n, m) entries.
  • X:rarest_label() gives each csr row the label with the lowest column count across the matrix. Ties go to the lower id, and an empty row gets -1.

Spans

Labelled intervals per document

spans stores per-document records with named integer columns, and csr-style offsets mark document boundaries. docs gathers whole documents into a new spans.

local spans = require("santoku.spans")
local ivec = require("santoku.ivec")
local arr = require("santoku.array")
local S = spans.create({ "s", "e", "ty" })
S:push(0, 3, 1):push(4, 7, 2):doc()
S:doc()
S:push(2, 5, 1):doc()
print("n:", S:n(), "docs:", S:n_docs())
print("offsets:", arr.concat(S:offsets():table(), " "))
print("starts:", arr.concat(S:col("s"):table(), " "))
print("names:", arr.concat(S:names(), " "))
local W = spans.create({
  offsets = ivec.create({ 0, 2, 2, 3 }),
  s = ivec.create({ 0, 4, 2 }),
  e = ivec.create({ 3, 7, 5 }),
  ty = ivec.create({ 1, 2, 1 }),
})
print("wrapped n:", W:n())
local D = W:docs(ivec.create({ 2, 0 }))
print("gathered offsets:", arr.concat(D:offsets():table(), " "))
return S:n()
Details
  • Build a spans by declaring columns and pushing records. doc closes each document, including empty ones.
  • Or wrap existing ivecs zero-copy.

Candidate generation

enumerate_subspans(max_span, masks) joins runs of up to max_span consecutive spans into candidate intervals, and returns an s, e spans. It's the generation step for span classification.

local spans = require("santoku.spans")
local ivec = require("santoku.ivec")
local arr = require("santoku.array")
local S = spans.create({ "s", "e", "ty" })
S:push(0, 2, 1):push(2, 5, 1):push(5, 6, 0):doc()
S:push(0, 3, 0):doc()
local all = S:enumerate_subspans(2)
print("unmasked:", all:n())
local inside = ivec.create({ 0, 1 })
local C = S:enumerate_subspans(2, { start = inside, stop = inside, inner = inside })
print("candidates:", C:n())
print("offsets:", arr.concat(C:offsets():table(), " "))
print("starts:", arr.concat(C:col("s"):table(), " "))
print("ends:", arr.concat(C:col("e"):table(), " "))
return C:n()
Details
  • masks is nil or a table of ivecs indexed by the ty column.
  • start lists the types a candidate may begin on, stop the types it may end on, and inner the types allowed in between.
  • A 0 entry bars a type, and an omitted mask allows every type.
  • Any mask needs a ty column.
  • Here type 0 is outside every entity.
  • Non-overlap selection over scored candidates is decide's span mode on the learn tab: https://santoku.dev/santoku-learn

Union and overlay

union merges two span sets per document and dedups on the full record tuple. overlay layers a list of span sets with list-order priority.

local spans = require("santoku.spans")
local arr = require("santoku.array")
local A = spans.create({ "s", "e", "ty" })
A:push(0, 2, 1):push(2, 5, 1):doc()
local B = spans.create({ "s", "e", "ty" })
B:push(2, 5, 1):push(5, 6, 2):doc()
local U = A:union(B)
print("union starts:", arr.concat(U:col("s"):table(), " "))
print("union types:", arr.concat(U:col("ty"):table(), " "))
local H = spans.create({ "s", "e", "ty" })
H:push(2, 6, 10):doc()
local L = spans.create({ "s", "e", "ty" })
L:push(0, 3, 20):push(6, 9, 21):doc()
local O = spans.overlay({ H, L })
print("overlay starts:", arr.concat(O:col("s"):table(), " "))
print("overlay types:", arr.concat(O:col("ty"):table(), " "))
return U:n()
Details
  • overlay keeps an earlier set's span wherever a later one would overlap it.
  • santoku.learn.evaluator scores span sets of this type.

Storage and containers

Vectors as SQL inputs

santoku-sqlite's carray virtual table binds a santoku-matrix vector as a table-valued SQL input. It reads the vector's backing store zero-copy at query time.

local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local ivec = require("santoku.ivec")
local arr = require("santoku.array")
local db = sql(sqlite.open_memory())
db.exec("create table items (id integer primary key, label text)")
local add = db.runner("insert into items (id, label) values (?, ?)")
add(1, "alpha")
add(2, "beta")
add(3, "gamma")
add(4, "delta")
local pick = db.all(
  "select label from items where id in (select value from carray(?)) order by id")
local ids = ivec.create({ 2, 4 })
print("labels:", arr.concat(pick(ids), ", "))
ids:set(0, 1)
print("after mutation:", arr.concat(pick(ids), ", "))
db.close()
return "ok"
Details
  • Mutate the vector and the next execution sees the new contents, with no serialization in between.
  • The sqlite tab shows carray joins inside full statements: https://santoku.dev/santoku-sqlite

Vectors on disk

Every object round-trips to a binary file with persist and a matching load, also on mtx, csr and spans. For arrays bigger than RAM, mmap_create allocates a zeroed file-backed vector.

local ivec = require("santoku.ivec")
local fvec = require("santoku.fvec")
local mtx = require("santoku.mtx")
local arr = require("santoku.array")
local v = ivec.create({ 1, 2, 3, 4 })
v:persist("vec.bin")
local w = ivec.load("vec.bin")
print("roundtrip:", arr.concat(w:table(), " "))
local m = fvec.mmap_create("big.bin", 1000000)
m:set(0, 1.5)
m:mmap_sync()
local r = fvec.mmap_open("big.bin")
print("first:", r:get(0))
local M = mtx.create({ data = r, n_rows = 1000, n_cols = 1000 })
print("disk-backed shape:", M:shape())
local raw = fvec.map("raw.f32")
print("mapped:", raw:size())
return M:shape()
Illustrative: runs outside the browser.
Details
  • mmap_sync flushes, and mmap_open reattaches later.
  • Since santoku-matrix 6.3.0, mmap_open(path, { readonly = true }) maps the file read-only. It opens a file you can read but not write.
  • Every mutating method on a read-only mapping raises "read-only mapping", and the file stays unchanged. Read methods and clone work as usual.
  • A read-only mapping is shared, so it sees writes made through another mapping of the file.
  • mmap_open raises "unknown option" for any key other than readonly.
  • An mmap vector can back an mtx, so a large encode writes straight to disk through the out= parameter.
  • map, on fvec, dvec and ivec, opens a headerless raw file as a private copy-on-write view, so writes never reach the file.
  • The example needs a real filesystem, so it's shown for reading.

Objects as strings

x:raw() returns an object as a string and X.from_raw(s) builds a new one from it. Both work on every vector type and on mtx, csr and spans.

local ivec = require("santoku.ivec")
local fvec = require("santoku.fvec")
local csr = require("santoku.csr")
local X = csr.from_pairs(ivec.create({ 0, 1 }), ivec.create({ 1, 0 }), 2, 2, fvec.create({ 0.25, 0.5 }))
local s = X:raw()
local Y = csr.from_raw(s)
print(X:eq(Y), getmetatable(Y).__pack)
local v = fvec.from_raw(fvec.create({ 1.5, -2 }):raw())
print(v:get(0), v:get(1))
return Y:raw() == s
Illustrative: runs outside the browser.
Details
  • A vector's string holds its element bytes only.
  • The mtx, csr and spans strings hold the same bytes their persist files do, and persist and load use the same code.
  • from_raw raises on a short string, trailing bytes or a bad header.
  • Bytes are in native order, so a string is for the same machine.
  • The metatable of each of these types sets __pack to its module name, such as "santoku.csr".
  • santoku.resty.ring's pack uses __pack to carry the object to another worker.
  • Hash maps, cuset and the store object have no __pack.
  • An mmap vector or a store view is a plain vector, so its raw string copies the elements.

One allocation, many vectors

A store declares typed vectors up front and backs them all with one zeroed allocation at open.

local store = require("santoku.store")
local mtx = require("santoku.mtx")
local s = store.create({ disk = true })
local codes = s:fvec(6)
local ids = s:ivec(2)
print("before open:", codes:size(), ids:size())
s:open()
print("after open:", codes:size(), ids:size())
print("on disk:", s:on_disk(), "bytes:", s:bytes())
local M = mtx.create({ data = codes, n_rows = 2, n_cols = 3 })
codes:set(5, 9)
print("through mtx:", M:get(1, 2))
s:close()
print("after close:", codes:size())
return M:shape()
Illustrative: runs outside the browser.
Details
  • With disk = true, a native build spills that allocation to an unlinked temp file under TMPDIR, /var/tmp by default. It checks free space first.
  • Under WebAssembly the allocation stays in RAM.
  • Views stay empty until open, can't grow, and drop to size 0 at close.
  • Declaring after open raises.
  • An mtx can wrap a view, which is how santoku-learn keeps large fold codes and tokenizer output off the heap.

Slot-based hash maps

iumap and its siblings (iuset, duset, zumap, cuset) are khash-style containers with a slot API. put inserts a key and get looks one up, and both return a slot.

local iumap = require("santoku.iumap")
local ivec = require("santoku.ivec")
local arr = require("santoku.array")
local m = iumap.create(0)
m:put(10)
m:setval(m:get(10), 100)
m:put(20)
m:setval(m:get(20), 200)
print("value for 10:", m:val(m:get(10)))
local count = 0
for _ in m:each() do
  count = count + 1
end
print("entries:", count)
m:destroy()
local v = ivec.create({ 10, 20, 30 })
local idx = v:index()
print("position of 20:", idx:val(idx:get(20)))
print("positions:", arr.concat(idx:gets(ivec.create({ 30, 99, 10 })):table(), " "))
return count
Illustrative: runs outside the browser.
Details
  • setval and val write and read the value at a slot, on maps only.
  • each iterates key and value pairs on the maps iumap and zumap.
  • ieach iterates every container, and destroy frees it.
  • ivec:index() builds an iumap from value to position, the O(1) reverse lookup used to intern ids.
  • iumap:gets(ids[, out]) maps an ivec of keys to an ivec of their values, with -1 on a miss.
  • The same containers are header-only C templates for extensions.

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