santoku-learn-llama
View on LuaRocksllama.cpp binding: gguf model embeddings as dense fvec codes for santoku-learn, plus a minimal raw and chat text generator
santoku-learn-llama is a deliberately small C binding to llama.cpp. It turns batches of text into dense embedding vectors for santoku-learn. It also gives a minimal text-generation entry point. It needs a gguf model at runtime, from a file or from memory.
Details
- The embeddings are a santoku-matrix fvec of n_samples x n_embd. That fvec is a dense block beside santoku-learn's sparse n-gram blocks.
- The whole API is three constructors (create, embedder, generator) and five methods across two object types.
- The modelling that consumes the embeddings lives in santoku-learn, including the retrieval reranker.
- The binding links a statically built llama.cpp, vendored at a pinned commit, with OpenMP on native builds.
- Since 5.1.0 the rock also builds for wasm, under node and in the browser. Since 7.0.0 it has a CUDA build.
- This page doesn't ship models, and nothing on it can run in the browser. Every example is display-only.
- The examples are distilled from the repo's regress suites under test/spec/santoku/learn/regress in the rock's source tarball.
Load an embedder
create(path) loads a gguf model in embed mode and returns an embedder. dims() returns the model's embedding size, n_embd.
local llama = require("santoku.learn.llama")
local enc = llama.create("model.gguf")
print("n_embd:", enc:dims())
local wide = llama.create("model.gguf", 64)
local tuned = llama.embedder("model.gguf", { n_seq = 16, n_threads = 8 })
print("same model, same dims:", wide:dims() == tuned:dims())
Details
- A number as the second argument sets n_seq, the batch width in sequences per forward pass. n_seq defaults to 32.
- An options table takes n_seq and n_threads. n_threads defaults to all OpenMP threads.
- embedder(path, ...) is the explicit form of the same constructor.
Memory loads and wasm builds
create({ data = bytes, n_seq, n_threads }) loads an embedder from a Lua string that holds the gguf file. embedder takes the same table. Path loading is unchanged.
local llama = require("santoku.learn.llama")
local fs = require("santoku.fs")
local err = require("santoku.error")
local enc = llama.create({ data = fs.readfile("model.gguf"), n_seq = 1 })
print("n_embd:", enc:dims())
print(err.pcall(llama.create, { data = "not a gguf model" }))
print(err.pcall(llama.create, { data = "not a gguf model", mode = "generate" }))
Details
- The load goes through fmemopen and llama_model_load_from_file_ptr.
- A buffer that doesn't hold a model raises "embedder: failed to load model from N bytes of data".
- data loads an embedder only. { data = ..., mode = "generate" } raises "create: data loads an embedder only, got mode 'generate'".
- The rock sets wasm_exceptions = true. So its wasm build runs under node and in the browser on santoku-make 7.3.0 or later.
- A page has no files, so in the browser a model loads from memory only.
- A web consumer's client block sets wasm_exceptions = true, which links wasi-libc. It lists "santoku-learn-llama >= 7.0.0, < 8.0.0" in its dependencies.
- That client needs Chrome 137, Firefox 131 or Safari 18.4.
- The make tab's C++ card has the details: https://santoku.dev/santoku-make#santoku-make--c-and-wasi-libc-in-wasm
Encode texts to dense codes
encode(texts) takes an array of strings and returns a row-major fvec with n_samples rows and n_embd columns, plus the dimension as a second return. Each row is L2-normalized by default.
local llama = require("santoku.learn.llama")
local enc = llama.create("model.gguf")
local codes, dim = enc:encode({
"the first document",
"the second document",
"the third document",
})
print("rows:", codes:size() / dim)
print("cols:", dim)
Details
- Pooling is model-driven. Models with a pooling type pool, and others use the last-token embedding. There is no pooling option.
- Each text is truncated to the model's training context.
- encode chunks the batch n_seq sequences at a time.
Normalization and in-place output
Pass false as encode's second argument to skip L2 normalization. Pass an fvec as the third argument, and encode writes into it in place and returns nothing.
local llama = require("santoku.learn.llama")
local fvec = require("santoku.fvec")
local enc = llama.create("model.gguf")
local texts = { "alpha document", "beta document" }
local raw = enc:encode(texts, false)
print("unnormalized rows:", raw:size() / enc:dims())
local out = fvec.mmap_create("codes.bin", #texts * enc:dims())
enc:encode(texts, true, out)
out:mmap_sync()
print("written in place:", out:size())
Details
- In-place output pairs with mmap-backed vectors to keep large corpora off the heap.
- The fvec must hold exactly #texts * dims() floats.
- Since 6.0.0, any other size raises "encode: output has N entries, expected M".
Dense codes for santoku-learn
Wrap encode's fvec in an mtx and append it to santoku-learn's block list. The embeddings then join the n-gram features as one more block.
local llama = require("santoku.learn.llama")
local ds = require("santoku.learn.dataset")
local mtx = require("santoku.mtx")
local optimize = require("santoku.learn.optimize")
local features = require("santoku.learn.features")
local pool = ds.read_20newsgroups("test/res/20news-bydate-train")
local test_set = ds.read_20newsgroups("test/res/20news-bydate-test")
local blocks = { { view = { "chars", "words" }, ngram = { chars = { 3, 5 }, words = { 1, 3 } },
votes = { norms = { "prob" } } } }
local F, Xtr = features.fit({ blocks = blocks, texts = pool.texts, class_stats = pool.labels })
local Xte = F:transform({ texts = test_set.texts })
local enc = llama.create(model_path)
local d = enc:dims()
Xtr[#Xtr + 1] = mtx.create({ data = enc:encode(pool.texts), n_rows = pool.n, n_cols = d })
Xte[#Xte + 1] = mtx.create({ data = enc:encode(test_set.texts), n_rows = test_set.n, n_cols = d })
local model = optimize.krr({
pool_blocks = Xtr,
pool_labels = pool.labels,
n_labels = 20,
n_landmarks = 1024 * 8,
search_landmarks = 1024 * 2,
})
local acc = model:score(Xte, { expected = test_set.labels })
print("test accuracy:", acc)
Details
- features.fit builds the n-gram csr block and its prob class-vote block, and F:transform builds the test blocks.
- The mtx takes the split size as n_rows and dims() as n_cols.
- The encoder centers a dense mtx block.
- scales weighs each block, so a pinned scales list holds three entries here.
- optimize.krr cross-validates over folds, so there's no validation split to encode.
- With no pins, optimize.krr searches the kernel (inv_nu, cosine_w, gamma, constant), lambda and block scales. search_trials = N caps the search.
- optimize.krr returns a model. model:score runs the test blocks through the encoder and ridge in tiles, and scores them with the decider.
- santoku-learn-llama 7.0.0 depends on santoku and santoku-matrix 6 only. Its examples here use the santoku-learn 19 API.
- read_20newsgroups strips each message by scikit-learn's remove=('headers', 'footers', 'quotes') rules.
Sentence pairs
The model sees exactly one string per sample. Pair tasks such as NLI and duplicate detection join the two sides into a single text before encode.
local llama = require("santoku.learn.llama")
local enc = llama.create(model_path)
local function pair_texts (lefts, rights, n)
local texts = {}
for i = 1, n do
texts[i] = lefts[i] .. "\n" .. rights[i]
end
return texts
end
local lefts = { "A man plays a guitar.", "A dog runs in a park." }
local rights = { "Someone is playing music.", "A cat sleeps indoors." }
local train_codes = enc:encode(pair_texts(lefts, rights, #lefts))
print("pair rows:", train_codes:size() / enc:dims())
Details
- The resulting fvec joins pool_blocks as an mtx block, as in the dense codes card above.
- No regress suite covers a pair dataset yet.
Extreme multi-label classification
For thousands of labels the embedder's role is unchanged: it adds a dense block beside the n-gram block. With search_trials = 0, a multi-label run needs a pinned decode_offset, and krr raises without one.
local llama = require("santoku.learn.llama")
local ds = require("santoku.learn.dataset")
local mtx = require("santoku.mtx")
local optimize = require("santoku.learn.optimize")
local features = require("santoku.learn.features")
local train, _, test_set = ds.read_eurlex57k("test/res/eurlex57k")
local blocks = { { view = { "chars", "words" }, ngram = { chars = { 3, 5 }, words = { 1, 3 } } } }
local F, Xtr = features.fit({ blocks = blocks, texts = train.texts })
local Xte = F:transform({ texts = test_set.texts })
local enc = llama.create(model_path)
local d = enc:dims()
Xtr[#Xtr + 1] = mtx.create({ data = enc:encode(train.texts), n_rows = train.n, n_cols = d })
Xte[#Xte + 1] = mtx.create({ data = enc:encode(test_set.texts), n_rows = test_set.n, n_cols = d })
local model = optimize.krr({
pool_blocks = Xtr,
pool_labels = train.labels,
n_labels = train.n_labels,
n_landmarks = 1024 * 16,
search_landmarks = 1024 * 2,
scales = { def = { 1.115754240990334, 0.89625471565531178 } },
decode_offset = { def = 0.28673768043518066 },
inv_nu = { def = 0.28756649440083631 },
cosine_w = { def = 0.17543128399115263 },
gamma = { def = 0.05802983041702893 },
lambda = { def = 3.4581597170761293e-05 },
search_trials = 0,
})
local f1 = model:score(Xte, { expected = test_set.labels })
print("test micro F1:", f1)
Details
- A multilabel head ranks as many labels per row as the most any training row carries.
- model:score labels the test split in tiles. It applies the decider's calibrated threshold over the ranked labels.
- The pins below come from learn-llama 7.0.0's eurlex suite with gte-small. That suite predates the kernel's constant term, so constant stays off here.
Semantic search
Embed the documents once, with a document prefix, into an mmap-backed fvec index. Encode each query on the fly with an asymmetric query prefix, and rank the rows with mtx:topk.
local llama = require("santoku.learn.llama")
local mtx = require("santoku.mtx")
local fvec = require("santoku.fvec")
local env = require("santoku.env")
local enc = llama.create(env.var("LLAMA_MODEL"))
local doc_prefix = env.var("LLAMA_MODEL_DOC_PREFIX", "")
local query_prefix = env.var("LLAMA_MODEL_QUERY_PREFIX", "")
local d = enc:dims()
local docs = {
"A cozy fantasy debut about a dragon who opens a bakery.",
"A hard science fiction thriller set on a mining station.",
"A memoir of a climber's first winter on the mountain.",
}
local texts = {}
for i = 1, #docs do texts[i] = doc_prefix .. docs[i] end
local index = fvec.mmap_create("docs.mcodes", #docs * d)
enc:encode(texts, true, index)
index:mmap_sync()
local codes = fvec.mmap_open("docs.mcodes")
local query_emb = enc:encode({ query_prefix .. "cozy fantasy debut" }, true)
local Mc = mtx.create({ data = codes, n_rows = #docs, n_cols = d })
local Mq = mtx.create({ data = query_emb, n_rows = 1, n_cols = d })
local hits = Mc:topk(Mq, 2)
print("best match:", docs[hits:neighbors():get(0) + 1])
Details
- Both prefixes come from the model card, through env vars.
- A later process reopens the index with fvec.mmap_open.
- Retrieval is cosine top-k over the normalized rows. mtx:topk returns a csr of row ids per query.
Rerank bm25 candidates
Take the top 100 bm25 candidates per query, then reorder them with santoku-learn's retrieval.reranker. The reranker blends the lexical score with the embedding dot product.
local llama = require("santoku.learn.llama")
local ds = require("santoku.learn.dataset")
local retrieval = require("santoku.learn.retrieval")
local eval = require("santoku.learn.evaluator")
local mtx = require("santoku.mtx")
local dvec = require("santoku.dvec")
local env = require("santoku.env")
local prefix = "Represent this sentence for searching relevant passages: "
local d = ds.read_beir("test/res/scifact", "test")
local X, Q = retrieval.lexical({ corpus_texts = d.corpus_texts, query_texts = d.query_texts })
local R = retrieval.bm25_ranker(X, Q)(1.2, 0.75, 100)
local enc = llama.create(env.var("LLAMA_RETRIEVAL_MODEL"))
local dim = enc:dims()
local qtexts = {}
for i = 1, d.n_queries do qtexts[i] = prefix .. d.query_texts[i] end
local D = mtx.create({ data = enc:encode(d.corpus_texts), n_rows = d.n_corpus, n_cols = dim })
local Qc = mtx.create({ data = enc:encode(qtexts), n_rows = d.n_queries, n_cols = dim })
local alpha = 0.96
local R1 = retrieval.reranker({ doc_codes = D }):rerank(R, Qc, dvec.create({ 1 - alpha, alpha }))
local _, ndcg = eval.ndcg(R1, d.qrels, 10)
print("alpha:", alpha, "ndcg@10:", ndcg)
Details
- retrieval.bm25_ranker runs csr:bm25 and csr:topk.
- santoku.sqlite.fts returns the same scores as retrieval.bm25_ranker (its specs compare them with ==).
- Queries get the search prefix that the model card gives, and documents get none. The suite uses bge-small-en-v1.5.
- rerank takes alpha as the weights dvec { 1 - alpha, alpha }.
- The 7.0.0 suite reranks at alpha 0.96 and pins ndcg@10 as below (rerank_ndcg and bm25_ndcg in scifact-llama.lua).
| Ranking | ndcg@10 |
|---|---|
| bm25 | 0.6663 |
| reranked | 0.7092 |
- The learn tab's retrieval cards cover the module.
- The suite reads the model path from LLAMA_RETRIEVAL_MODEL.
Generator
Raw prompts
generator(path, opts) loads a model in decode mode. generate(prompt, opts) returns only the completion.
local llama = require("santoku.learn.llama")
local g = llama.generator(model_path, { n_ctx = 2048 })
local prompt = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
.. "Say hi in one word.<|eot_id|>"
.. "<|start_header_id|>assistant<|end_header_id|>\n\n"
local out = g:generate(prompt, {
max_tokens = 16, temperature = 0.0, stop = { "\n", "<|" },
})
print("vocab:", g:dims())
print("completion:", out)
Details
- n_ctx defaults to 4096 and is capped at the model's training context.
- Stop strings truncate the output, and the matched stop is removed.
- End-of-generation tokens end the output naturally.
- On a generator, dims() is the vocabulary size.
- This card is distilled from the generate-llama regress suite.
Chat templates
Construct with template = "llama3" or "chatml", and chat() builds the prompt from system, user and assistant_prefix fields. Only user is required.
local llama = require("santoku.learn.llama")
local err = require("santoku.error")
local g = llama.generator(model_path, { n_ctx = 2048, template = "llama3" })
local out = g:chat(
{ system = "You write terse one-line answers.", user = "Say hi in one word." },
{ max_tokens = 16, temperature = 0.0, stop = { "\n" } })
print("completion:", out)
local raw = llama.create(model_path, { mode = "generate" })
local ok, msg = err.pcall(function ()
return raw:chat({ user = "hi" })
end)
print("no template configured:", ok, msg)
Details
- The default template is "raw", and chat() raises on it. Use generate() for raw prompts.
- create(path, { mode = "generate", ... }) is the dispatching form of the same constructor.
- Both forms also take n_threads and seed.
Sampling options
generate defaults to max_tokens 64 and temperature 0, which is greedy. With a temperature above 0, generate samples through the chain below.
local llama = require("santoku.learn.llama")
local g = llama.generator(model_path, { n_ctx = 4096, seed = 42 })
local greedy = g:generate("Once upon a time", { max_tokens = 64 })
local sampled = g:generate("Once upon a time", {
max_tokens = 128,
temperature = 0.8,
top_k = 40,
top_p = 0.95,
min_p = 0.05,
repeat_penalty = 1.1,
seed = 7,
stop = { "\n\n" },
})
print("greedy is deterministic:", greedy == g:generate("Once upon a time"))
Details
- The chain is repeat penalty, top_k 40, top_p 0.95, min_p 0.05, temperature, then a seeded distribution.
- The repeat penalty runs only when repeat_penalty exceeds 1, over the last 64 tokens.
- seed defaults to the constructor's seed, which defaults to 0.
- generate errors on an empty prompt or on a prompt that fills n_ctx.
Requirements and CUDA builds
The rock builds against a vendored llama.cpp pinned by commit, and links its static archives with OpenMP and libstdc++. At runtime you supply a gguf model file.
local env = require("santoku.env")
local model_path = env.var("LLAMA_MODEL", nil)
if not model_path then
print("LLAMA_MODEL not set. Skipping.")
return
end
local llama = require("santoku.learn.llama")
print("cuda build:", llama.cuda == true)
local enc = llama.create(model_path)
print("n_embd:", enc:dims())
Details
- The regress suites are benchmarks. They read LLAMA_MODEL for embedders, LLAMA_RETRIEVAL_MODEL for retrieval or LLAMA_GEN_MODEL for the generator.
- A regress suite skips when its variable is unset.
- The classification and retrieval suites also need their test/res datasets.
- The classification suites (eurlex, imdb, newsgroups, banking77) add a gte-small block to santoku-learn's matching spec. scifact reranks with bge-small.
- llama.cpp logging is silenced.
- The backend is refcounted. It's freed when the last embedder or generator is collected.
- toku test --cuda, toku build --cuda and toku install --cuda build llama.cpp with GGML_CUDA on. _CUDA=1 in the environment does the same as toku install --cuda.
- toku build --cuda needs santoku-cli 3.6.0 or later.
- A CUDA build links cuBLAS and the CUDA runtime. llama.cpp's default model parameters then offload every layer to the GPU.
- A CUDA build sets llama.cuda to true. It passes llama.cpp's ggml_cuda_init, Device and load_tensors log lines to stderr.
- With no GPU visible, the first embedder raises "embedder: no CUDA device". The first generator raises "generator: no CUDA device".
- CPU and wasm builds are unchanged, and llama.cuda is nil there.