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

The pealang/ai_ml.py module in PeaLang 3.1.39 exposes a small set of transformer-style primitives through the built-in stats namespace. They are dependency-free, but several are deliberately simplified stubs: create_embedding and random_search are seeded, while BytePairTokenizer.train() and export_to_onnx() are not fully deterministic. Call them directly as stats....; PeaLang import requires a quoted path to another .pea file, so there is no bare import stats here.

Byte-pair tokenization

let tok = stats.BytePairTokenizer()
tok.train(corpus, 8000)
let ids = tok.encode("the cat sat on the mat")
print ids

BytePairTokenizer(vocab=None, merges=None) accepts an optional vocabulary and merge list. train(text, vocab_size=256), encode(text) and decode(ids) form the whole surface. The current trainer is simplified: it stores characters as the vocabulary and accepts vocab_size without using it. It also does not rebuild inv_vocab, so decode() returns <?> for newly trained IDs unless a matching vocab was supplied at construction. Treat this as a character-level fixture, not a production BPE tokenizer.

Embeddings

let emb = stats.create_embedding(ids, 256)

create_embedding(tokens, embedding_dim=768, vocab_size=50257) returns one vector per token. It uses a fixed internal seed and ignores the token values and vocab_size, so it is a deterministic shape fixture for tests and teaching — not a learned or semantic embedding table.

Scaled dot-product attention

let pair = stats.scaled_dot_product_attention(q, k, v, causal_mask)
let out = pair[0]
let weights = pair[1]

scaled_dot_product_attention(q, k, v, mask=None) computes Q·Kᵀ, scales by 1/√d_k, applies the mask, uses an internal numerically stable softmax, multiplies by V, and returns (output, weights). softmax is defined in ai_ml.py but is not exported to stats; call the attention function instead of stats.softmax(...).

Transformer blocks

let block = stats.TransformerBlock(128, 4)
let y = block.forward(x, causal_mask)

TransformerBlock(d_model, n_heads=8, d_ff=2048, dropout=0.1) stores its configuration and exposes forward(x, mask=None). The source is explicitly a simplified stub: Q/K/V are the input itself, attention is single-head, and it returns the attention output; feed-forward, residual, layer-normalization and dropout behaviour are not implemented. Use it to trace tensor shapes, not as a full transformer.

Similarity and distance

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

These three stats helpers take two vectors and return a scalar. They match the vector/RAG primitives from vector_rag.py (VectorStore, hybrid_search, bm25_score), which are also available in stats. Because the embedding stub above is not semantic, the scores are only as meaningful as the vectors you supply.

Worked example: wiring a tiny ticket search

let tok = stats.BytePairTokenizer()
tok.train(ticket_corpus, 4000)
let store = stats.VectorStore()
for t in tickets {
  let vec = stats.create_embedding(tok.encode(t.text), 128)[0]
  store.add(t.text, vec, { "id": t.id })
}
let query_vec = stats.create_embedding(tok.encode("refund for damaged item"), 128)[0]
let hits = store.hybrid_search("refund for damaged item", query_vec, 5)

This wires the real signatures, but create_embedding returns one vector per token, so the example indexes a single token vector before storing it. VectorStore.add(text, embedding, metadata=None) expects a 1-D vector and returns an index, and hybrid_search(query, query_embedding, top_k=5, alpha=0.5) ranks stored documents. It is a retrieval scaffold, not a working semantic search: the tokenizer is character-level and the embedding stub does not encode meaning. Swap in real embeddings before trusting the ranking.

Guided practice

← Previous Next →