Documentation

Hesper.Inference.Sampling

Sampling Algorithms for Text Generation #

Implements various sampling strategies for autoregressive language model inference.

Sampling Strategies #

1. Greedy Decoding (Deterministic) #

next_token = argmax(logits)

Use case: Reproducible outputs, factual tasks Pros: Deterministic, fast Cons: Repetitive, lacks creativity

2. Top-k Sampling #

top_k_logits, indices = topk(logits, k)
probs = softmax(top_k_logits / temperature)
next_token = sample(indices, probs)

Use case: Creative generation with controlled diversity Pros: Balances quality and diversity Cons: Fixed k may be too restrictive or permissive

3. Nucleus (Top-p) Sampling #

sorted_probs = sort(softmax(logits), descending=True)
cumsum = cumulative_sum(sorted_probs)
nucleus = sorted_probs[cumsum <= p]
next_token = sample(nucleus)

Use case: Adaptive diversity based on distribution Pros: Adapts to confidence (dynamic cutoff) Cons: More compute than top-k

Temperature Scaling #

Temperature τ controls randomness:

scaled_logits = logits / τ

τ → 0:   Deterministic (greedy)
τ = 1:   Normal distribution
τ > 1:   More random/creative

References #

Data Structures #

Sampling configuration

Instances For
    Equations
    • One or more equations did not get rendered due to their size.
    Instances For

      Core Utilities #

      Find argmax (index of maximum value)

      @param logits Array of logit scores @return Index of maximum value

      Equations
      Instances For
        @[irreducible]
        def Hesper.Inference.Sampling.argmax.loop (logits : Array Float) (idx maxIdx : Nat) (maxVal : Float) :
        Equations
        • One or more equations did not get rendered due to their size.
        Instances For

          Apply temperature scaling

          @param logits Original logits @param temperature Temperature value (τ > 0) @return Scaled logits

          Equations
          Instances For

            Compute softmax probabilities

            Uses numerically stable version: exp(x - max(x))

            @param logits Log-probabilities @return Probabilities (sum to 1.0)

            Equations
            • One or more equations did not get rendered due to their size.
            Instances For

              Greedy Sampling #

              Greedy sampling: select token with highest probability

              Algorithm:

              next_token = argmax(logits)
              

              @param logits Logit scores [vocab_size] @return Selected token ID

              Equations
              Instances For

                Top-k Sampling #

                Find indices of top-k largest values

                @param logits Array of scores @param k Number of top elements @return (top_k_values, top_k_indices)

                Equations
                • One or more equations did not get rendered due to their size.
                Instances For
                  @[irreducible]
                  Equations
                  Instances For

                    Sample from categorical distribution

                    Simple implementation using linear search through cumulative probabilities.

                    @param probs Probability distribution (must sum to ~1.0) @param randomValue Random value in [0, 1) @return Sampled index

                    Equations
                    Instances For
                      @[irreducible]
                      def Hesper.Inference.Sampling.categoricalSample.loop (probs : Array Float) (randomValue : Float) (idx : Nat) (cumulative : Float) :
                      Equations
                      • One or more equations did not get rendered due to their size.
                      Instances For
                        def Hesper.Inference.Sampling.sampleTopK (logits : Array Float) (k : Nat) (temperature randomValue : Float) :

                        Top-k sampling: sample from k tokens with highest probability

                        Algorithm:

                        1. Find top-k logits and their indices
                        2. Apply temperature scaling
                        3. Compute softmax over top-k
                        4. Sample from categorical distribution
                        

                        @param logits Logit scores [vocab_size] @param k Number of top candidates @param temperature Sampling temperature @param randomValue Random number in [0, 1) for sampling @return Selected token ID

                        Equations
                        • One or more equations did not get rendered due to their size.
                        Instances For

                          Nucleus (Top-p) Sampling #

                          def Hesper.Inference.Sampling.sampleNucleus (logits : Array Float) (p temperature randomValue : Float) :

                          Nucleus (top-p) sampling: sample from smallest set with cumulative probability >= p

                          Algorithm:

                          1. Sort logits in descending order
                          2. Compute softmax probabilities
                          3. Find nucleus: tokens where cumsum(probs) <= p
                          4. Renormalize and sample from nucleus
                          

                          @param logits Logit scores [vocab_size] @param p Cumulative probability threshold (typically 0.9) @param temperature Sampling temperature @param randomValue Random number in [0, 1) for sampling @return Selected token ID

                          Equations
                          • One or more equations did not get rendered due to their size.
                          Instances For
                            @[irreducible]
                            Equations
                            • One or more equations did not get rendered due to their size.
                            Instances For
                              @[irreducible]
                              Equations
                              • One or more equations did not get rendered due to their size.
                              Instances For

                                Repetition Penalty #

                                Apply repetition penalty to logits. Tokens that appeared in prevTokens have their logits divided (if positive) or multiplied (if negative) by the penalty factor. penalty = 1.0 means no penalty. Typical values: 1.1 - 1.3.

                                Equations
                                • One or more equations did not get rendered due to their size.
                                Instances For

                                  High-Level Sampling Interface #

                                  Sampling strategy

                                  Instances For
                                    Equations
                                    • One or more equations did not get rendered due to their size.
                                    Instances For
                                      Equations
                                      • One or more equations did not get rendered due to their size.
                                      def Hesper.Inference.Sampling.sample (logits : Array Float) (strategy : Strategy) (randomValue : Float := 0.5) :

                                      Sample next token using specified strategy

                                      @param logits Logit scores [vocab_size] @param strategy Sampling strategy @param randomValue Random value in [0, 1) (only used for stochastic strategies) @return Selected token ID

                                      Equations
                                      Instances For

                                        Random Number Generation #

                                        Simple linear congruential generator (LCG) for reproducible sampling

                                        Parameters: Numerical Recipes (a = 1664525, c = 1013904223, m = 2^32)

                                        @param seed Current seed @return (random_float in [0,1), new_seed)

                                        Equations
                                        Instances For

                                          Random number generator state

                                          Instances For
                                            Equations
                                            • One or more equations did not get rendered due to their size.
                                            Instances For

                                              Create RNG from optional seed

                                              Equations
                                              Instances For

                                                Generate next random float

                                                Equations
                                                Instances For

                                                  Sampling with RNG #

                                                  Sample with automatic RNG threading

                                                  @param logits Logit scores @param strategy Sampling strategy @param rng Random number generator state @return (selected_token, new_rng)

                                                  Equations
                                                  Instances For

                                                    Utilities #

                                                    def Hesper.Inference.Sampling.printStats (logits : Array Float) (selectedToken : Nat) :

                                                    Print sampling statistics

                                                    @param logits Logit scores @param selectedToken Sampled token

                                                    Equations
                                                    • One or more equations did not get rendered due to their size.
                                                    Instances For