API Text #
Text and 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,
- “next-token prediction” sample builders used by GPT-style examples,
- 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 generated
byte streams that are not valid UTF-8. For valid UTF-8 strings, decode (encode s) = s; model
output remains printable even when the byte stream is invalid UTF-8.
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 character-level GPT examples
(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), soencodeis total. - 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.
Token ids are read from tokens, missing positions use padId, and every batch row receives the
same window. Use causalLmSampleOneHotBatchRows when rows should come from different corpus
offsets.
Instances For
One-hot encode one causal-LM input window per batch row.
This is the input-only companion to causalLmSampleOneHotBatchRows, used by generation code that
has prefixes but no shifted training targets.
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]. Every batch row
receives the same window, which is useful for prompt evaluation, deterministic checks, and synthetic
sequence tasks.
Instances For
Build a batched supervised causal-LM sample from one token window per batch row.
Use this for GPT-style minibatches with distinct corpus windows. causalLmSampleOneHotBatch remains
useful when every batch row should repeat a fixed prompt or synthetic sequence.
Instances For
Byte-Corpus Windows #
Read one byte token from a raw corpus, returning padId past the end.
This is byte-level rather than BPE-level: examples can train 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 or conversion command for that dataset.
Instances For
Read a raw byte corpus and optionally enforce a minimum size.
allowSmallData is an explicit override for bounded local runs. Corpus-training commands can set
minBytes to the scale they expect and require users to acknowledge smaller 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 bounded corpora stay total; callers can still enforce a minimum corpus size before 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.
The helper is token-array based, so 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.
If the prompt is present in the corpus, a portion of the sampled windows covers nearby text. That keeps generation reports tied to text the model actually saw during training.
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 terminal output.
Display-only: this does not change tokenizer semantics. It keeps examples readable when a predicted byte sequence contains quotes, backslashes, tabs, or newlines.
Instances For
Sampling Helpers (Top-k) #
Shared text-generation flags for GPT-style examples.
- prompt : String
Prompt used to seed autoregressive generation.
- generate : ℕ
Number of new tokens to append.
- temperature : Float
Softmax temperature. Must be positive.
- topK : ℕ
Top-k cutoff.
1gives greedy decoding. - repeatPenalty : Float
Penalty subtracted for repeated recent tokens.
0disables it. - repeatWindow : ℕ
Number of recent tokens considered by the repeat penalty.
0disables the window. - seed : ℕ
Deterministic RNG seed for sampling.
- asciiOnly : Bool
Restrict generated ids to a model-specific ASCII allow-list.
Instances For
Instances For
Instances For
Parse the generation flags shared by GPT-style examples.
The model file still owns its training/data flags. This helper only handles prompt, sampling, repeat penalty, deterministic seed, and ASCII restriction.
Instances For
Instances For
Parse generation flags using a full GenerationOptions value as defaults.
This is the public API shape used by model commands: they provide a concrete default prompt and sampling policy, and the shared parser handles the stable CLI surface.
Instances For
Text Workflow Option Records #
Required text-corpus path plus the explicit small-data option used by local corpus trainers.
- dataFile : System.FilePath
UTF-8 or raw-byte corpus path selected by
--data-file. - allowSmallData : Bool
Allow local runs below the normal corpus-size floor.
Instances For
Instances For
Optional text-corpus path selected by --data-file, with caller-supplied default.
- path : System.FilePath
Local text corpus path.
Instances For
Instances For
Parse an optional --data-file flag using the supplied default path.
Instances For
Optional second corpus pass after the main training run.
- finetuneFile? : Option System.FilePath
Optional corpus used for a second fine-tuning pass.
- finetuneSteps : ℕ
Number of optimizer steps used on that second corpus when present.
Instances For
Parse the optional --finetune-file / --finetune-steps pair.
The caller supplies the default step count so commands can reuse their main training-step default.
Instances For
Optional GPT-2 BPE tokenizer bundle plus an optional bounded-text cap.
- bpeVocab? : Option System.FilePath
Optional GPT-2
vocab.jsonpath. Must be paired withbpeMerges?. - bpeMerges? : Option System.FilePath
Optional GPT-2
merges.txtpath. Must be paired withbpeVocab?. Optional text-character cap for bounded local BPE runs.
Instances For
Parse the optional GPT-2 BPE tokenizer bundle.
--bpe-vocab and --bpe-merges must appear together; --max-chars is independent.
Instances For
Shared terminal-REPL toggle used by interactive text examples.
- interactive : Bool
Keep the trained model alive and read prompts from stdin.
Instances For
Instances For
Parse the shared --interactive flag used by text examples with a terminal prompt loop.
Instances For
Instances For
Parse the shared --prompt / --generate flags.
Instances For
Text TrainLog Notes #
TrainLog note fields for generation-capable text commands.
The stable generation surface is prompt, continuation length, temperature/top-k, repetition
control, RNG seed, and ASCII-only filtering. Model commands can prepend dataset or architecture
notes through extra.
Instances For
Write a before/after loss log for a generation-capable text training command.
Instances For
Write a before/after loss log for a prompt-based text training command.
Instances For
Shared "load one parameter pack, then sample" option surface.
- paramsPath : System.FilePath
JSON bits checkpoint loaded before sampling starts.
Instances For
Instances For
Parse the shared saved-parameter sampling flags used by inference-only text commands.
Instances For
Text Training Option Combinators #
Logged-training options plus the terminal-REPL toggle.
Instances For
Instances For
Build the shared logged-training + interactive option record.
Instances For
Standard training flags plus the terminal-REPL toggle.
Instances For
Instances For
Build the shared train-flags + interactive option record.
Instances For
Parse the shared "train + interactive" option surface.
Instances For
Logged-training options for promptable interactive text commands.
Instances For
Build the shared logged-training + prompt + interactive option record.
Instances For
Parse the shared "logged train + prompt + interactive" option surface.
Instances For
Corpus-training options for promptable text commands.
This combines the common corpus, fine-tune, BPE, prompt, logging, and interactive controls without tying them to a particular model implementation.
- corpus : TextCorpusOptions
Required primary corpus path plus the small-data override.
- finetune : FinetuneOptions
Optional second corpus pass after the main training run.
- bpe : BpeCorpusOptions
Optional GPT-2 BPE tokenizer bundle.
Instances For
Parse the shared "corpus + logged train + prompt + interactive + optional fine-tune/BPE" surface.
Instances For
Training options for text commands that train and then sample.
Instances For
Instances For
Build the shared train + generation option record.
Instances For
Training options for cyclic text trainers that also expose --windows.
Instances For
Build the shared train + generation + windows option record.
Instances For
Parse the standard "train + generate + windows" option surface.
Instances For
Training options for text commands that support save/load checkpoints.
Instances For
Build the shared train + generation + windows + checkpoint option record.
Instances For
Parse the shared "train + generate + windows + checkpoint" option surface.
Instances For
Training options for text commands with generic batch and context-length controls.
- batch : ℕ
Number of independently sampled training windows per optimizer step.
- seqLen : ℕ
Context length in tokens or characters.
Instances For
Parse the shared "train + generate + windows + checkpoint + batch + seq-len" option surface.
Instances For
Training options for text commands with sampling, checkpointing, and an interactive prompt loop.
Instances For
Build the full train + generation + windows + checkpoint + interactive option record.
Instances For
Parse the full "train + generate + windows + checkpoint + interactive" option surface.
Instances For
Return the indices of the top k scores (largest first).
This deterministic utility is used by the GPT-style examples. The direct O(k*vocab) implementation
is adequate for the vocabulary sizes and top-k values used by these executable examples.
Instances For
Apply a repetition penalty by subtracting repeatPenalty * count(token) for tokens
appearing in recent.
This is a local sampling heuristic; it is not the same as the presence or frequency penalties used by hosted APIs, but it gives examples a deterministic way to discourage immediate repetition.
Instances For
Printable ASCII bytes plus newline.
Instances For
Escape one byte token for display inside a quoted string.
Instances For
Escape byte ids as a one-line quoted display string.
Instances For
Sample one token id from scores using temperature + top-k sampling.
The randomness is deterministic given (seed, counter), so a run with the same flags produces the
same sampled text.
Instances For
Autoregressively extend token ids with a model-provided score callback.
The callback receives the padded context window and the sequence position whose logits should be
used for the next token. The shared policy crops to the last seqLen tokens, pads, applies repeat
penalties, samples by top-k/temperature, and appends one token per step.
Instances For
Extract the vocabulary-score row at one sequence position.
Instances For
Extract a vocabulary-score row from batched logits.
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.