PeaBox Lab › PeaLang › Learn › Chapter 35 › Lesson 1

Part V — The Modern Experience Layer · Chapter 35 · Lesson 1 of 2

Tokenization, embeddings and attention in PeaLang

v2.3.0 added guides/pealang/ai_ml.py: the small set of primitives you need to build, probe and sanity-check transformer-style models without leaving the language. Pure Python, no native dependencies, deterministic seeds throughout.

Byte-pair tokenization

let tok = analysis.BytePairTokenizer()
tok.train(corpus, { "vocab_size": 8000 })
let ids = tok.encode("the cat sat on the mat")
let text = tok.decode(ids)

BytePairTokenizer builds a mergeable subword vocabulary from your corpus — the same core algorithm behind production tokenizers. Train it on your domain's text, not on Wikipedia, if your domain has jargon: a tokenizer that understands your vocabulary tokenizes it in far fewer pieces than one that treats your terms as foreign. Fewer tokens means cheaper embeddings, cheaper attention, and better signal per position — this is the same economics that keep specialized models small.

Embeddings

let emb = analysis.create_embedding(tokens, { "dim": 256, "seed": 42 })

create_embedding produces a seeded, reproducible embedding table — the starting point for small models, fixtures and teaching. Determinism given a seed matters more than it looks: it means your tests, your golden vectors and your teammate's machine all agree bit-for-bit on the inputs to the model, which is the only way small-model debugging stays sane.

Scaled dot-product attention

let out = analysis.scaled_dot_product_attention(q, k, v, {
  "mask": causal_mask
})

The real thing, one function: Q·Kᵀ, scaled by √d, masked, softmaxed, multiplied by V — with a numerically stable softmax included (analysis.softmax). Masking is explicit, which is what you want: the causal mask, the padding mask, or no mask at all, each visible in the call and each testable in isolation.

Transformer blocks

let block = analysis.TransformerBlock({ "d_model": 128, "heads": 4 })
let y = block.forward(x)

A TransformerBlock wires multi-head attention with a position-wise feed-forward network and residual connections. It is deliberately minimal — a teaching and prototyping vehicle, and the right size for a small-domain model trained on a laptop. If you outgrow it, you'll know, and the migration path is to a real accelerator framework — not to a bigger block in the same stdlib.

Similarity and distance

let a = analysis.cosine_similarity(v1, v2)
let b = analysis.euclidean_distance(v1, v2)
let c = analysis.dot_product(v1, v2)

The full trio: cosine for direction, Euclidean for magnitude-aware distance, dot product for unnormalized similarity. These compose directly with the vector/RAG primitives from v1.7.0 (VectorStore, hybrid_search, bm25_score) — same value space, same conventions. If you built retrieval on v1.7.0, these are drop-in scoring functions, not a new paradigm.

Worked example: tiny semantic search over tickets

let tok = analysis.BytePairTokenizer()
tok.train(ticket_corpus, { "vocab_size": 4000 })
let index = {}
for t in tickets {
  let vec = analysis.create_embedding(tok.encode(t.text), { "dim": 128, "seed": 7 })
  index[t.id] = analysis.VectorStore.add(vec, t)
}
let hits = analysis.hybrid_search(index, "refund for damaged item", 5)

Train the tokenizer on your tickets, embed with a fixed seed, store in the vector store, hybrid-search with a user query. That is a working semantic search — no external service, no embedding API, no per-query cost. It will not beat a frontier embedding API on nuance; it will be good enough to route 70% of support mail, and it runs inside your compliance boundary.

Guided practice

← Previous Next →