TorchLean API

NN.API.Text.Generation

Text Generation #

Score filtering, top-k sampling, logit extraction, decoding, and causal masks used by language-model examples.

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 TorchLean.text.penalizeRepeats (scores : Array Float) (recent : List ) (repeatPenalty : Float) :

      Apply a repetition penalty by subtracting $\mathrm{repeatPenalty}\,\mathrm{count}(\mathrm{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 TorchLean.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 TorchLean.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 TorchLean.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 TorchLean.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 TorchLean.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 TorchLean.text.autoregressiveTokenIds.loop (seqLen padId : ) (opts : GenerationOptions) (scoreWindow : List IO (Array Float)) (allowId : Bool) (sanitize : ) (ids : List ) :
                        IO (List )
                        def TorchLean.text.logitScoresAt {seqLen vocab : } (logits : Spec.Tensor Float (Spec.Shape.dim seqLen (Spec.Shape.dim vocab Shape.scalar))) (pos : ) :

                        Extract the vocabulary-score row at one sequence position.

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

                          Extract a vocabulary-score row from batched logits.

                          Instances For
                            def TorchLean.text.argmaxTokenIdsFromLogits {α : Type} [LT α] [DecidableRel fun (x1 x2 : α) => x1 > x2] {seqLen vocab : } (logits : Spec.Tensor α (Spec.Shape.dim seqLen (Spec.Shape.dim vocab Shape.scalar))) :

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

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

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

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

                                Instances For
                                  def TorchLean.text.decodeArgmaxBatchLogits {α : Type} [LT α] [DecidableRel fun (x1 x2 : α) => x1 > x2] (t : Tokenizer) {batch seqLen vocab : } (logits : Spec.Tensor α (Spec.Shape.dim batch (Spec.Shape.dim seqLen (Spec.Shape.dim vocab Shape.scalar)))) (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 \leq i$, meaning position $i$ may attend to itself and earlier positions but not to future positions.

                                    Instances For