API Text #
Small text / NLP helpers for TorchLean examples.
TorchLean’s executable runtime expects inputs as floating tensors, so runtime and autograd code can handle them with the same typed tensor APIs as parameters. For language models this means we commonly represent token ids as one-hot / token-distribution tensors of shape:
(batch × seqLen × vocab)
and implement “token embeddings” as a matrix multiply against an embedding table.
This module provides:
- a tokenizer interface (with a byte-level tokenizer),
- helpers to turn token streams into one-hot tensors,
- small “next-token prediction” sample builders used by GPT-style demos,
- display helpers for turning model logits back into readable token predictions.
Tokenizers #
Convert token ids to bytes, truncating each id modulo 256.
Instances For
Decode byte tokens as UTF-8 when possible, falling back to a byte-wise display mode for
invalid generated byte streams. This keeps decode (encode s) = s for arbitrary UTF-8 strings while
remaining total for demos that sample invalid byte sequences.
Instances For
Byte-level UTF-8 tokenizer: each byte is one token in [0,256).
Instances For
Build a character-level tokenizer from an explicit alphabet.
This is the TorchLean analogue of the stoi/itos tables used in many educational GPT demos
(including Karpathy's "char-gpt" / minGPT walkthroughs): encode maps characters to ids
0..alphabet.size-1, and decode maps ids back to characters.
Notes:
- This tokenizer is deterministic given
alphabet; callers are responsible for choosing how to construct the alphabet (e.g.sorted(set(data))). - Characters not present in the alphabet map to
unkId(default 0). This keepsencodetotal. - Ids outside
[0, vocabSize)decode to theunkChar(default?).
Instances For
One-Hot Token Tensors #
One-hot vector for a single token id (Vec vocab). Out-of-range ids map to all-zeros.
Instances For
One-hot encode a fixed-length token sequence as a matrix (seqLen × vocab).
Instances For
One-hot encode a fixed-size batch of token sequences as (batch × seqLen × vocab).
Instances For
Causal LM Samples #
Build a (x, y) pair for next-token prediction from a token stream.
x[t] = oneHot(tokens[t])
y[t] = oneHot(tokens[t+1])
If the stream is too short, we pad with padId.
Instances For
Build a batched causal-LM (x, y) pair from one token window per batch row.
This is the text analogue of image/tabular minibatching:
- row
ireceives its own token windowtokensAt i; x[i,t]istokensAt i[t];y[i,t]istokensAt i[t+1];- short rows are padded with
padId.
GPT-style examples share this batching logic. The contract is explicit: a text batch is a typed
tensor of shape (batch, seqLen, vocab), just like the vision loader collates rows into
(batch, C, H, W).
Instances For
One-hot encode a causal-LM input window as a batched tensor.
This is the reusable version of the hand-written helpers used by the GPT-style demos: token ids are
read from tokens, missing positions use padId, and every batch row receives the same window.
Instances For
Build a batched supervised next-token sample from a token stream.
The target is shifted by one position: x[t] = tokens[t], y[t] = tokens[t+1]. This is deliberately
small and deterministic, which makes it useful for examples such as byte-level GPT, BPE smoke tests,
and the minGPT-style addition task.
Instances For
Build a batched supervised causal-LM sample from one token window per batch row.
Use this for real GPT-style minibatches. causalLmSampleOneHotBatch is still useful for prompt
probes or smoke tests where every batch row intentionally repeats the same window; this function is
the one model trainers should call when they want distinct windows inside the batch.
Instances For
Byte-Corpus Windows #
Read one byte token from a raw corpus, returning padId past the end.
This is intentionally byte-level rather than BPE-level: examples can train small causal language
models directly from a text file without depending on an external tokenizer artifact. GPT-2
BPE support lives in NN.API.Text.Bpe.
Instances For
Extract a fixed-length byte-token window from a raw corpus.
offset is measured in bytes, not Unicode characters. That is the right behavior for byte-level
causal language modeling and avoids hidden UTF-8 slicing assumptions.
Instances For
Corpus Helpers #
Read a UTF-8 text file with a caller-supplied preparation hint.
The examples pass their executable name and a concrete hint so failures point users to the exact download/conversion command for that demo.
Instances For
Read a raw byte corpus and optionally enforce a minimum size.
allowSmallData is for smoke tests. Serious corpus-training examples can set minBytes to a large
value and require users to pass an explicit opt-in flag for small local files.
Instances For
Parse a text-corpus flag set and return (text, remainingArgs).
Supported forms:
--data-file PATH- any named alias in
aliases, such as("--tiny-shakespeare", path) - no data flag, which uses
defaultPath
Deterministic sliding-window offset for a byte corpus.
Instances For
Number of legal start positions for a (seqLen + 1) next-token window.
We return at least one start position so small smoke corpora stay total; callers still usually validate corpus size separately before real training.
Instances For
Deterministic minGPT-style random offsets for one training batch.
The result is a function Fin batch → Nat: one corpus start offset per row. We derive the random
key from (seed, step) and then draw row offsets by the row index, so the run is reproducible
without using ambient IO randomness. This is the text equivalent of a shuffled DataLoader epoch.
Instances For
Build token windows for one deterministic random text batch.
Each row gets seqLen + 1 ids so downstream causal-LM helpers can form both x and shifted y.
This helper is intentionally token-array based: byte, character, BPE, and synthetic tokenizers can
all produce an Array Nat and reuse the same batching semantics.
Instances For
Choose training-window offsets, biased toward a prompt occurrence when the corpus contains it.
This makes tutorial generation probes less random: if the prompt is present in the corpus, a chunk of the sampled windows will cover nearby text.
Instances For
Causal LM Display Helpers #
Return a fixed-length token window from a text string.
offset = 0 is the model prompt window; offset = 1 is the usual next-token target window for
causal language modeling. Missing tokens are padded with padId, matching
causalLmXYOneHotMatFloat.
Instances For
Decode a fixed token window extracted by tokenWindow.
Instances For
Escape a short text fragment for one-line demo output.
This is intentionally display-only: it does not change tokenizer semantics. It just keeps examples readable when the predicted byte sequence contains quotes, backslashes, tabs, or newlines.
Instances For
Simple Sampling Helpers (Top-k) #
Return the indices of the top k scores (largest first).
This is a small, deterministic utility used by the GPT-style examples. It is intentionally simple:
k is small in typical demo settings, and the vocab sizes are modest enough that O(k*vocab) is
fine for interactive sampling.
Instances For
Apply a lightweight repetition penalty by subtracting repeatPenalty * count(token) for tokens
appearing in recent.
This is a deliberately simple heuristic; it is not the same as presence/frequency penalties in commercial APIs, but it is enough to make tutorial sampling less degenerate.
Instances For
Sample one token id from scores using temperature + top-k sampling.
The randomness is deterministic given (seed, counter). This is important for examples: we can
re-run a tutorial with the same flags and get the same sampled text.
Instances For
Decode a matrix of token logits by taking argmax independently at each sequence position.
The shape is (seqLen × vocab), i.e. one logits vector per token position. This helper is for
inspection/debugging and is not differentiable.
Instances For
Decode (seqLen × vocab) logits as text using a tokenizer.
Instances For
Extract batchIdx from batched logits and return the per-position argmax token ids.
Instances For
Decode one batch row of (batch × seqLen × vocab) logits as text.
Instances For
Causal (autoregressive) attention mask of shape (seqLen × seqLen).
Entry (i, j) is true iff j ≤ i, meaning position i may attend to itself and earlier
positions but not to future positions.