Vectors and search

Vectors and search by meaning

An embedding model turns a text into a vector: a list of numbers, a few hundred to a few thousand, such that texts with close meanings get vectors that point in close directions. “How do I brew green tea?” and “steeping sencha” come out near each other, without sharing a word. Comparing vectors finds texts by meaning, and RAG (retrieval-augmented generation) gives an AI model the pieces of your own documents that answer a question.

Luma has a vector type, vec, in the language, and three mods: embed.luma makes vectors of texts, vectors.luma keeps them and finds the nearest, and cuts texts into chunks.

vec

A vec holds numbers as 4-byte floats, packed, as embedding models give them: half the memory of a [float], and its math runs at native speed in luma run too.

cat: vec = vec([0.9, 0.1, 0.3])
kitten: vec = vec([0.85, 0.15, 0.35])
car: vec = vec([0.1, 0.9, 0.2])
print(cat.cosine(kitten))
print(cat.cosine(car))
print(cat.dot(car))
print(cat.norm())
print(len(cat))
print(cat[0])
print(cat)
nums: [float] = convert(cat)
print(nums)

Output:

0.9960653528971317
0.2712947196900118
0.24000000119209286
0.9539391828283589
3
0.8999999761581421
vec(3)
[0.8999999761581421, 0.10000000149011612, 0.30000001192092896]
Function or methodWhat it does
vec(list)a vec of a [float]: each number the nearest 4-byte float
vec(data)a vec of a buffer or [byte]: 4 bytes a number, lowest byte first (error 11 if the length isn’t a multiple of 4)
convertto a vec from a [float], a buffer, a [byte], or a json array of numbers (as embedding APIs answer); from a vec to a [float] or a buffer
a.cosine(b)the cosine similarity: 1 the same direction, 0 unrelated, -1 opposite; 0 if either is all zeros
a.dot(b)the dot product
a.norm()the length: the square root of a.dot(a)
a[i], len(a)a number (a float), and how many there are
a.bytes()a copy of its bytes, a buffer: for files and databases (a SQLite BLOB)
  • A number becomes the nearest 4-byte float: 0.9 is 0.8999999761581421.
  • dot and cosine take vecs of one length; others raise error 11: the vecs have different lengths: 3 and 2. An index outside it is error 2.
  • The math is done in 8-byte floats, in order, so luma run and a built program give exactly the same results. Comparing a question with 100,000 vectors of 1,024 numbers takes about 0.3 seconds.
  • print shows a vec’s length; convert it to a [float] to see its numbers.
  • A vec is shared like a buffer, and can’t be changed: make a new one.

Arithmetic

Vecs also have the arithmetic that AI models are made of. Each gives a new vec (or a float), worked out number by number in 8-byte floats and rounded to 4-byte ones, so luma run and a built program give the same bits:

fn show(v: vec) {
    nums: [float] = convert(v)
    print(nums)
}
x: vec = vec([1.0, -2.0, 0.5, 4.0])
w: vec = vec([0.5, 0.5, 2.0, 1.0])
show(x.add(w))
show(x.mul(w).scale(2.0))
print("${x.sum()} ${x.max()} ${x.index(x.max())}")
e: vec = x.plus(-x.max()).exp()
show(e.scale(1.0 / e.sum()))
show(x.part(1, 3).join(w.part(0, 1)))

Output:

[1.5, -1.5, 2.5, 5.0]
[1.0, -2.0, 2.0, 8.0]
3.5 4.0 3
[0.04599423334002495, 0.002289918251335621, 0.02789691463112831, 0.9238189458847046]
[-2.0, 0.5, 0.5]
MethodWhat it gives
a.add(b), a.mul(b)the numbers added, or multiplied, one by one (vecs of one length)
a.plus(x), a.scale(x)x added to each number; each times x
a.exp(), a.silu()e to the power of each; SiLU, x / (1 + e^-x), of each
a.sum(), a.max()the numbers added up; the largest (error 2 for an empty vec)
a.index(x)where x first is, -1 if it isn’t there: a.index(a.max()) is where the largest is
a.part(i, j), a.join(b)the numbers from i up to j; a’s, then b’s
a.rotate(cos, sin, neox)pairs of numbers turned by the angles whose cosines and sines are given, in each piece of 2 × len(cos): pairs (2i, 2i+1), or (i, i + len(cos)) with neox (RoPE, as transformers place a token)

The softmax above is exp of each number less the largest, divided by their sum.

Matrices of model weights: qmat

A qmat is a matrix as GGUF model files keep their weights (see the gguf mod): the bytes of a tensor and its ggml type, F32, F16, BF16, Q8_0, Q4_0, Q5_0, Q4_K or Q6_K. Its product with a vec is the heart of running a model.

fn show(v: vec) {
    nums: [float] = convert(v)
    print(nums)
}
w: qmat = qmat(vec([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).bytes(), 0, 2, 3)
print(w)
show(w.mul(vec([1.0, 0.5, -1.0])))
show(w.row(1))
keys: qmat = qmat(2)
keys.add(vec([1.0, 0.0]))
keys.add(vec([0.0, 1.0]))
print(keys)
show(keys.mul(vec([0.6, 0.8])))
show(keys.tmul(vec([0.25, 0.75])))

Output:

qmat(2 × 3, F32)
[-1.0, 0.5]
[4.0, 5.0, 6.0]
qmat(2 × 2, F32)
[0.6000000238418579, 0.800000011920929]
[0.25, 0.75]
Function or methodWhat it does
qmat(data, kind, rows, cols)a matrix of a buffer of weights, as a GGUF tensor holds them (m.read(t) or m.map(t) of the gguf mod), of ggml type kind: 0 F32, 1 F16, 30 BF16, 8 Q8_0, 2 Q4_0, 6 Q5_0, 12 Q4_K, 14 Q6_K. The matrix is on the buffer’s bytes, not a copy, so a mapped file’s stay the file’s.
qmat(cols)an empty matrix of 4-byte floats, with cols numbers a row
m.mul(x)the matrix times x (a vec of cols numbers): a vec of rows numbers
m.row(i)row i as a vec (a token’s embedding)
m.add(r)adds a row at the end (a matrix of floats only): a cache of keys or values
m.tmul(w)w (a vec of rows numbers) times the matrix: its rows, each times its number of w, added up
m.rows(), m.cols(), m.kind()its size and ggml type
  • For the quantized types, mul makes x 8-bit numbers too, 32 a block with a scale each, as llama.cpp does: each block’s products are then a whole number, exact, and the blocks’ results are added in order. The result is the same, to the bit, in luma run and a built program, and within a millionth of what numpy gives for the same numbers.
  • A size that doesn’t match (bytes, columns, a vec’s length) is error 11, which says what was expected.
  • The products and the vec arithmetic are native code: Go in luma run; in a built program AVX2 where the processor has it (most made since 2013-2015), SSE2 on the others. A built program multiplies a 1536 × 768 matrix of Q8_0 by a vec in about 0.3 ms with SSE2, about half that with AVX2; luma run is 10 times slower. The environment variable LUMA_NOAVX=1 keeps a built program to SSE2. A result that isn’t a number (a nan) is always the same one, so that too is the same in all of them.
  • A large m.mul(x) is shared among threads, one for each 262,144 weights, up to half as many as the computer has processors for the program (most processors run two threads on each core, and the second only slows the first here), or the number in the environment variable LUMA_THREADS: LUMA_THREADS=1 keeps it to one. Each row is worked out the same way whatever thread does it, so the result is the same bits with any number of threads. The program itself still runs on one thread: the others only multiply, while mul waits for them.

Making vectors: the embed mod

mods/embed.luma asks an embedding model for vectors. Anthropic doesn’t have one of its own, and recommends Voyage AI; OpenAI’s work too, and Ollama runs one on your own computer, free, with nothing leaving it:

import "embed"

e: embed.model = embed.voyage()                  // VOYAGE_API_KEY; the model voyage-4
e: embed.model = embed.openai()                  // OPENAI_API_KEY; text-embedding-3-small
e: embed.model = embed.ollama()                  // ollama pull nomic-embed-text first

v: vec = e.one("Green tea is steeped at 80 degrees.")
q: vec = e.query("How hot should the water be?")
vs: [vec] = e.many(chunks)
Function or methodWhat it does
embed.voyage(key, name)Voyage AI; voyage-4 if no name
embed.openai(key, name)OpenAI; text-embedding-3-small if no name
embed.ollama(name, url)Ollama; nomic-embed-text and http://localhost:11434 if not given
e.one(text)the vector of a text to be found
e.query(text)the vector of a question to look with (Voyage makes these a little differently, which finds better; the others make both the same)
e.many(texts)the vectors of many texts, in their order, in as few requests as the API takes
e.dimensions(n)shorter vectors, for models that can (Voyage: 2048, 1024, 512, 256; OpenAI’s text-embedding-3)
e.url(address)another address: a proxy, or Ollama on another computer
  • Without a key, VOYAGE_API_KEY or OPENAI_API_KEY is read.
  • Vectors of different models, or of one model with different dimensions, can’t be compared: keep to one.
  • A rate limit or a server error is tried again 3 times. Errors: embed.AUTH (101: no key, or a wrong one), embed.FAILED (100: anything else the API says).

An index: the vectors mod

mods/vectors.luma keeps vectors by an id, with anything about them (a json: the text, its file, its page), and finds the ones nearest a question:

import "vectors"

idx: vectors.index = vectors.index()
idx.add("tea.md#1", v, {"file": "tea.md", "text": chunk})
idx.search(q, 3).walk(h) {
    print("${h.score} ${h.id} ${h.meta["text"]}")
}
idx.save(file("notes.idx"))
idx = vectors.load(file("notes.idx"))
Function or methodWhat it does
vectors.index()an empty index
idx.add(id, v, meta)adds a vector; one with the same id is replaced
idx.remove(id), idx.has(id), idx.size()takes one out, asks for one, counts them
idx.search(q, k)the k nearest to q, nearest first: [vectors.hit] with id, score (the cosine similarity) and meta
idx.save(f), vectors.load(f)writes the index to a file (beside it first, then moved into place), and reads it back
  • The search is exact: the question is compared with every vector. That is fast enough for a million vectors.
  • All the vectors of an index have one length; another is error vectors.SIZE (101). A file that isn’t an index is vectors.BROKEN (100).

Cutting texts into chunks

A model makes one vector of a whole text, so a long document is cut into pieces first, each about one subject. vectors.chunks(text, size, overlap) cuts a text into pieces of at most size characters (1000 if not given): between paragraphs where it can, a Markdown heading always starting a new piece, else between sentences, else between words. Each piece starts with the last words of the one before, up to overlap characters (150), so a thought cut in two is whole in one of them.

Putting it together: questions about your notes

import "embed"
import "vectors"
import "claude"

e: embed.model = embed.voyage()
idx: vectors.index = vectors.index()
folder("notes").find("**/*.md").walk(f) {
    path: str = convert(f)
    parts: [str] = vectors.chunks(f.read())
    vs: [vec] = e.many(parts)
    (0..len(parts) - 1).walk(i) {
        idx.add("${path}#${i}", vs[i], {"file": path, "text": parts[i]})
    }
}
idx.save(file("notes.idx"))

ai: claude.client = claude.connect()
question: str = "What did I decide about the garden?"
found: [str] = []
idx.search(e.query(question), 5).walk(h) {
    found[] = "From ${h.meta["file"]}:\n${h.meta["text"]}"
}
print(ai.ask("Answer from these notes only:\n\n${found.join("\n\n")}\n\nQuestion: ${question}"))

Not available yet

  • An approximate index (HNSW) for many millions of vectors, and filtering a search by meta.
  • A vec as an obj field’s default: give the field no default, and a vec when making the object.