TorchLean API

NN.API.Text.Core

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:

Tokenizers #

Tokenizer interface (encode/decode).

  • vocabSize :

    Vocabulary size (token ids are expected to be in [0, vocabSize)).

  • encode : StringList

    Encode a string into token ids.

  • decode : List String

    Decode token ids back into a string.

Instances For

    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
          def NN.API.text.Tokenizer.ofAlphabet (alphabet : Array Char) (unkId : := 0) (unkChar : Char := '?') :

          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), so encode is total.
          • Ids outside [0, vocabSize) decode to the unkChar (default ?).
          Instances For
            def NN.API.text.Tokenizer.encodeVec (t : Tokenizer) (n : ) (s : String) (padId : := 0) :

            Encode and pad/truncate to a fixed length, returning a length-indexed Vector.

            Instances For
              def NN.API.text.Tokenizer.encodeBatchVec (t : Tokenizer) (batch seqLen : ) (ss : List String) (padId : := 0) :
              Vector (Vector seqLen) batch

              Encode a batch of strings, padding/truncating each to length seqLen.

              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
                  def NN.API.text.tokensToOneHotMatFloat {seqLen vocab : } (tokens : Vector seqLen) :

                  One-hot encode a fixed-length token sequence as a matrix (seqLen × vocab).

                  Instances For
                    def NN.API.text.tokensToOneHotBatchFloat {batch seqLen vocab : } (tokens : Vector (Vector seqLen) batch) :

                    One-hot encode a fixed-size batch of token sequences as (batch × seqLen × vocab).

                    Instances For

                      Causal LM Samples #

                      def NN.API.text.causalLmXYOneHotMatFloat (seqLen vocab : ) (tokens : List ) (padId : := 0) :

                      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
                        def NN.API.text.causalLmXYOneHotBatchRowsFloat (batch seqLen vocab : ) (tokensAt : Fin batchList ) (padId : := 0) :

                        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 i receives its own token window tokensAt i;
                        • x[i,t] is tokensAt i[t];
                        • y[i,t] is tokensAt 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
                          def NN.API.text.causalLmXOneHotBatch {α : Type} [Semantics.Scalar α] [Runtime.Scalar α] (batch seqLen vocab : ) (tokens : List ) (padId : := 0) :
                          Tensor.Tensor α (Spec.Shape.dim batch (Shape.Mat seqLen vocab))

                          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
                            def NN.API.text.causalLmXOneHotBatchRows {α : Type} [Semantics.Scalar α] [Runtime.Scalar α] (batch seqLen vocab : ) (tokensAt : Fin batchList ) (padId : := 0) :
                            Tensor.Tensor α (Spec.Shape.dim batch (Shape.Mat seqLen vocab))

                            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
                              def NN.API.text.causalLmSampleOneHotBatch {α : Type} [Semantics.Scalar α] [Runtime.Scalar α] (batch seqLen vocab : ) (tokens : List ) (padId : := 0) :
                              SupervisedSample α (Spec.Shape.dim batch (Shape.Mat seqLen vocab)) (Spec.Shape.dim batch (Shape.Mat seqLen vocab))

                              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
                                def NN.API.text.causalLmSampleOneHotBatchRows {α : Type} [Semantics.Scalar α] [Runtime.Scalar α] (batch seqLen vocab : ) (tokensAt : Fin batchList ) (padId : := 0) :
                                SupervisedSample α (Spec.Shape.dim batch (Shape.Mat seqLen vocab)) (Spec.Shape.dim batch (Shape.Mat seqLen vocab))

                                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 #

                                  def NN.API.text.byteAtD (bytes : ByteArray) (i : ) (padId : := 0) :

                                  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
                                    def NN.API.text.byteTokenWindow (bytes : ByteArray) (n : ) (offset padId : := 0) :

                                    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 #

                                      def NN.API.text.Corpus.readUtf8File (exeName : String) (path : System.FilePath) (missingHint : String) :

                                      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
                                        def NN.API.text.Corpus.readByteFile (exeName : String) (path : System.FilePath) (allowSmallData : Bool) (minBytes seqLen : ) :

                                        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
                                          partial def NN.API.text.Corpus.takeUtf8Input (exeName : String) (defaultPath : System.FilePath) (aliases : List (String × System.FilePath)) (missingHint : String) :

                                          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
                                          def NN.API.text.Corpus.byteOffset (bytes : ByteArray) (i seqLen : ) :

                                          Deterministic sliding-window offset for a byte corpus.

                                          Instances For
                                            def NN.API.text.Corpus.tokenOffset (tokens : Array ) (i seqLen : ) :

                                            Deterministic sliding-window offset for an already-tokenized corpus.

                                            Instances For
                                              def NN.API.text.Corpus.usableTokenStarts (tokenCount seqLen : ) :

                                              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
                                                def NN.API.text.Corpus.tokenArrayWindow (tokens : Array ) (n offset : ) (padId : := 0) :

                                                Extract a fixed token window from an array-backed token corpus.

                                                Instances For
                                                  def NN.API.text.Corpus.randomBatchOffsets (tokenCount seqLen batch seed step : ) :
                                                  Fin batch

                                                  Deterministic minGPT-style random offsets for one training batch.

                                                  The result is a function Fin batchNat: 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
                                                    def NN.API.text.Corpus.randomBatchTokenWindows (tokens : Array ) (batch seqLen seed step : ) (padId : := 0) :
                                                    Fin batchList

                                                    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

                                                      Check whether pat occurs in xs at offset off.

                                                      Instances For

                                                        Find the first offset where pat appears in xs.

                                                        Instances For
                                                          def NN.API.text.Corpus.promptAwareOffsets (tokenCount seqLen windows : ) (promptOffset? : Option ) :

                                                          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 #

                                                            def NN.API.text.tokenWindow (t : Tokenizer) (n : ) (input : String) (offset padId : := 0) :

                                                            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
                                                              def NN.API.text.decodeWindow (t : Tokenizer) (n : ) (input : String) (offset padId : := 0) :

                                                              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. 1 gives greedy decoding.

                                                                  • repeatPenalty : Float

                                                                    Penalty subtracted for repeated recent tokens. 0 disables it.

                                                                  • repeatWindow :

                                                                    Number of recent tokens considered by the repeat penalty. 0 disables the window.

                                                                  • seed :

                                                                    Deterministic RNG seed for sampling.

                                                                  • asciiOnly : Bool

                                                                    Restrict generated ids to a model-specific ASCII allow-list.

                                                                  Instances For

                                                                    Defaults for parseGenerationOptions.

                                                                    Instances For

                                                                      Parse --ascii-only, accepting either a bare flag or true/false value.

                                                                      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

                                                                          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

                                                                              Parse the required --data-file corpus flag and optional --allow-small-data switch.

                                                                              Instances For

                                                                                Optional text-corpus path selected by --data-file, with caller-supplied default.

                                                                                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.

                                                                                        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

                                                                                              Parse the shared --interactive flag used by text examples with a terminal prompt loop.

                                                                                              Instances For

                                                                                                Shared prompt plus continuation-length options for simple text-generation commands.

                                                                                                • prompt : String

                                                                                                  Prompt used for before/after reports and generation.

                                                                                                • generate :

                                                                                                  Number of generated tokens or characters after training.

                                                                                                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

                                                                                                      TrainLog note fields for prompt-based text commands that do not expose the full sampling surface.

                                                                                                      Instances For
                                                                                                        def NN.API.text.writeGenerationTrainLog (log : Runtime.Training.LogDestination) (title : String) (steps : ) (loss0 loss1 : Float) (gen : GenerationOptions) (generated? : Option String := none) (extra : Array String := #[]) :

                                                                                                        Write a before/after loss log for a generation-capable text training command.

                                                                                                        Instances For
                                                                                                          def NN.API.text.writePromptTrainLog (log : Runtime.Training.LogDestination) (title : String) (steps : ) (loss0 loss1 : Float) (gen : PromptGenerationOptions) (generated? : Option String := none) (extra : Array String := #[]) :

                                                                                                          Write a before/after loss log for a prompt-based text training command.

                                                                                                          Instances For

                                                                                                            Shared "load one parameter pack, then sample" option surface.

                                                                                                            Instances For

                                                                                                              Parse the shared saved-parameter sampling flags used by inference-only text commands.

                                                                                                              Instances For

                                                                                                                Text Training Option Combinators #

                                                                                                                Build the shared logged-training + interactive option record.

                                                                                                                Instances For

                                                                                                                  Build the shared train-flags + interactive option record.

                                                                                                                  Instances For
                                                                                                                    def NN.API.text.InteractiveTrainOptions.parse (exeName : String) (args : List String) (defaultLogJson : System.FilePath) (defaultSteps : ) (defaultLr : Float) (allowZeroSteps : Bool := false) :

                                                                                                                    Parse the shared "train + interactive" option surface.

                                                                                                                    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.

                                                                                                                          Instances For

                                                                                                                            Parse the shared "corpus + logged train + prompt + interactive + optional fine-tune/BPE" surface.

                                                                                                                            Instances For

                                                                                                                              Build the shared train + generation option record.

                                                                                                                              Instances For

                                                                                                                                Build the shared train + generation + windows option record.

                                                                                                                                Instances For
                                                                                                                                  def NN.API.text.WindowedTrainGenerationOptions.parse (exeName : String) (args : List String) (defaultLogJson : System.FilePath) (defaultSteps : ) (defaultLr : Float) (defaultWindows : ) (genDefaults : GenerationOptions) (allowZeroSteps : Bool := false) :

                                                                                                                                  Parse the standard "train + generate + windows" option surface.

                                                                                                                                  Instances For

                                                                                                                                    Build the shared train + generation + windows + checkpoint option record.

                                                                                                                                    Instances For
                                                                                                                                      def NN.API.text.CheckpointedWindowedTrainGenerationOptions.parse (exeName : String) (args : List String) (defaultLogJson : System.FilePath) (defaultSteps : ) (defaultLr : Float) (defaultWindows : ) (genDefaults : GenerationOptions) (allowZeroSteps : Bool := false) :

                                                                                                                                      Parse the shared "train + generate + windows + checkpoint" option surface.

                                                                                                                                      Instances For

                                                                                                                                        Training options for text commands with generic batch and context-length controls.

                                                                                                                                        Instances For
                                                                                                                                          def NN.API.text.BatchedCheckpointedWindowedTrainGenerationOptions.parse (exeName : String) (args : List String) (defaultLogJson : System.FilePath) (defaultSteps : ) (defaultLr : Float) (defaultWindows defaultBatch defaultSeqLen : ) (genDefaults : GenerationOptions) (allowZeroSteps : Bool := false) :

                                                                                                                                          Parse the shared "train + generate + windows + checkpoint + batch + seq-len" option surface.

                                                                                                                                          Instances For

                                                                                                                                            Build the full train + generation + windows + checkpoint + interactive option record.

                                                                                                                                            Instances For
                                                                                                                                              def NN.API.text.InteractiveCheckpointedWindowedTrainGenerationOptions.parse (exeName : String) (args : List String) (defaultLogJson : System.FilePath) (defaultSteps : ) (defaultLr : Float) (defaultWindows : ) (genDefaults : GenerationOptions) (allowZeroSteps : Bool := false) :

                                                                                                                                              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

                                                                                                                                                  Greedy argmax index.

                                                                                                                                                  Instances For
                                                                                                                                                    def NN.API.text.penalizeRepeats (scores : Array Float) (recent : List ) (repeatPenalty : Float) :

                                                                                                                                                    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
                                                                                                                                                      def NN.API.text.restrictScores (scores : Array Float) (allowId : Bool) :

                                                                                                                                                      Mask scores by an allow-list predicate (disallowed ids get a very negative score).

                                                                                                                                                      This is mainly used by byte-level examples to optionally restrict output to printable ASCII.

                                                                                                                                                      Instances For
                                                                                                                                                        def NN.API.text.prepareScoresForGeneration (scores : Array Float) (recent : List ) (repeatPenalty : Float) (allowId : Bool := fun (x : ) => true) :

                                                                                                                                                        Apply repeat penalty and an allow-list mask before sampling.

                                                                                                                                                        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
                                                                                                                                                                def NN.API.text.sampleTopKIndex (scores : Array Float) (temperature : Float) (topK seed counter : ) :

                                                                                                                                                                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
                                                                                                                                                                  def NN.API.text.chooseNextToken (scores : Array Float) (opts : GenerationOptions) (counter : ) (recent : List := []) (allowId : Bool := fun (x : ) => true) :

                                                                                                                                                                  Select the next token from prepared logits using greedy or temperature/top-k sampling.

                                                                                                                                                                  Instances For
                                                                                                                                                                    def NN.API.text.autoregressiveTokenIds (seqLen padId : ) (promptIds : List ) (opts : GenerationOptions) (scoreWindow : List IO (Array Float)) (allowId : Bool := fun (x : ) => true) (sanitize : := fun (tok : ) => tok) :

                                                                                                                                                                    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
                                                                                                                                                                      partial def NN.API.text.autoregressiveTokenIds.loop (seqLen padId : ) (opts : GenerationOptions) (scoreWindow : List IO (Array Float)) (allowId : Bool) (sanitize : ) (ids : List ) :
                                                                                                                                                                      IO (List )
                                                                                                                                                                      def NN.API.text.logitScoresAt {seqLen vocab : } (logits : Tensor.Tensor Float (Shape.Mat seqLen vocab)) (pos : ) :

                                                                                                                                                                      Extract the vocabulary-score row at one sequence position.

                                                                                                                                                                      Instances For
                                                                                                                                                                        def NN.API.text.batchLogitScoresAt {batch seqLen vocab : } (logits : Tensor.Tensor Float (Spec.Shape.dim batch (Shape.Mat seqLen vocab))) (batchIdx : Fin batch) (pos : ) :

                                                                                                                                                                        Extract a vocabulary-score row from batched logits.

                                                                                                                                                                        Instances For
                                                                                                                                                                          def NN.API.text.argmaxTokenIdsFromLogits {α : Type} [LT α] [DecidableRel fun (x1 x2 : α) => x1 > x2] {seqLen vocab : } (logits : Tensor.Tensor α (Shape.Mat seqLen vocab)) :

                                                                                                                                                                          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
                                                                                                                                                                            def NN.API.text.decodeArgmaxLogits {α : Type} [LT α] [DecidableRel fun (x1 x2 : α) => x1 > x2] (t : Tokenizer) {seqLen vocab : } (logits : Tensor.Tensor α (Shape.Mat seqLen vocab)) :

                                                                                                                                                                            Decode (seqLen × vocab) logits as text using a tokenizer.

                                                                                                                                                                            Instances For
                                                                                                                                                                              def NN.API.text.argmaxTokenIdsFromBatchLogits {α : Type} [LT α] [DecidableRel fun (x1 x2 : α) => x1 > x2] {batch seqLen vocab : } (logits : Tensor.Tensor α (Spec.Shape.dim batch (Shape.Mat seqLen vocab))) (batchIdx : Fin batch) :

                                                                                                                                                                              Extract batchIdx from batched logits and return the per-position argmax token ids.

                                                                                                                                                                              Instances For
                                                                                                                                                                                def NN.API.text.decodeArgmaxBatchLogits {α : Type} [LT α] [DecidableRel fun (x1 x2 : α) => x1 > x2] (t : Tokenizer) {batch seqLen vocab : } (logits : Tensor.Tensor α (Spec.Shape.dim batch (Shape.Mat seqLen vocab))) (batchIdx : Fin batch) :

                                                                                                                                                                                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.

                                                                                                                                                                                  Instances For