sample

package
v0.27.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 16, 2026 License: Apache-2.0 Imports: 6 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sample provides various sampling strategies for autoregressive generation.

It also includes a BeamSearch implementation in "graph", used by decode.Decoder to implement beam search decoding.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Greedy

func Greedy(logits *Node) *Node

Greedy: select max-logit token.

func SampleWithStrategy

func SampleWithStrategy(
	ctx RNG,
	logits *graph.Node,
	strategy Strategy,
	temperature float64,
	topK int,
	topP float64,
) *graph.Node

SampleWithStrategy dispatches to greedy|temperature|top_k|top_p.

BeamSearch rquires specialized handling, and will lead to an error if used here.

func StrategyStrings

func StrategyStrings() []string

StrategyStrings returns a slice of all String values of the enum

func Temperature

func Temperature(rng RNG, logits *Node, temperature float64) *Node

Temperature: scale by temperature and sample via Gumbel-ArgMax.

The rng is used for random number generation, a context.Context implements this interface.

func TopKWithTemperature

func TopKWithTemperature(rng RNG, logits *graph.Node, k int, temperature float64) *graph.Node

TopKWithTemperature: mask non-top-k to -inf, then temperature.

The rng is used for random number generation, a context.Context implements this interface.

func TopP

func TopP(rng RNG, logits *Node, p float64, temperature float64) *Node

TopP: nucleus sampling by masking tokens covering ~p mass.

The rng is used for random number generation, a context.Context implements this interface.

Types

type BeamSearchConfig

type BeamSearchConfig struct {
	// contains filtered or unexported fields
}

BeamSearchConfig configures beam search decoding for autoregressive generation. Beam search explores multiple candidate sequences in parallel (beams), selecting the most likely sequences at each step. This typically produces higher quality outputs than greedy decoding but requires more computation.

Usage:

  • beamSize: Number of parallel beams (2-10 is common, higher = better quality but slower)
  • lengthPenalty: Adjusts preference for longer sequences (>1.0 favors longer, <1.0 favors shorter)
  • eosTokenId: Token ID that marks end-of-sequence
  • numReturnSeqs: How many sequences to return (typically 1, must be <= beamSize)

func NewBeamSearch

func NewBeamSearch(beamSize, eosTokenId int) *BeamSearchConfig

NewBeamSearch creates a beam search configuration with default settings.

Parameters:

  • beamSize: Number of parallel beams to maintain (typically 2-10)
  • eosTokenId: Token ID marking end-of-sequence (-1 to disable EOS handling)

Returns a BeamSearchConfig with defaults:

  • lengthPenalty: 1.0 (no penalty)
  • maxLength: 100
  • minLength: 0
  • numReturnSeqs: 1 (return only the best sequence)
  • earlyStopping: true (stop when all beams hit EOS)

Example:

beamCfg := sample.NewBeamSearch(4, eosTokenId).
    WithLengthPenalty(0.9).     // slightly favor shorter sequences
    WithMaxLength(150).
    WithMinLength(10).          // require at least 10 tokens
    WithNumReturnSequences(3)   // return top 3 sequences

Then one would use beamCfg.Step() in a loop to generate tokens. See decode.Decoder.Decode() for a higher-level API.

func (*BeamSearchConfig) EarlyStopping

func (c *BeamSearchConfig) EarlyStopping() bool

EarlyStopping returns whether early stopping is enabled.

func (*BeamSearchConfig) SelectBest

func (c *BeamSearchConfig) SelectBest(
	sequences *Node,
	scores *Node,
) (bestSequences, bestScores *Node)

SelectBest selects the top scoring sequences from beam search results. After beam search completes, this method extracts the best numReturnSeqs sequences from each batch based on their cumulative scores.

Parameters:

  • sequences: All beam sequences [batch*beam, seq_length]
  • scores: Cumulative scores for each beam [batch*beam]

Returns:

  • bestSequences: Top sequences [batch*numReturnSeqs, seq_length]
  • bestScores: Corresponding scores [batch*numReturnSeqs]

Example: If beamSize=4 and numReturnSeqs=1, this returns only the single best sequence from each batch.

func (*BeamSearchConfig) Step

func (c *BeamSearchConfig) Step(
	logits *Node,
	currentSequences *Node,
	beamScores *Node,
	currentLength int,
) (nextSequences, nextBeamScores, isFinished *Node)

Step performs one decoding step of beam search. This is a low-level method for implementing beam search generation. It takes current beam states and model logits, then selects the top-k candidates for the next step based on cumulative scores.

The method:

  1. Converts logits to log probabilities
  2. Suppresses EOS tokens if below minLength
  3. Adds current beam scores to get cumulative scores
  4. Selects top beamSize candidates across all beams
  5. Updates sequences with new tokens and tracks finished beams

Parameters:

  • logits: Model output logits [batch*beam, vocab_size]
  • currentSequences: Current token sequences [batch*beam, current_length]
  • beamScores: Cumulative log probability scores [batch*beam]
  • currentLength: Current sequence length (for minLength enforcement)

Returns:

  • nextSequences: Updated sequences [batch*beam, current_length+1]
  • nextBeamScores: Updated cumulative scores [batch*beam]
  • isFinished: Boolean mask indicating which beams hit EOS [batch*beam]

Note: This method is typically called in a loop by higher-level generation code. Most users should use decode.Decoder.Decode() with strategy="beam_search" instead.

func (*BeamSearchConfig) WithEarlyStopping

func (c *BeamSearchConfig) WithEarlyStopping(early bool) *BeamSearchConfig

WithEarlyStopping controls whether to stop when all beams have hit EOS. If true (default), stops as soon as all beams produce EOS tokens. If false, continues until maxLength is reached.

func (*BeamSearchConfig) WithLengthPenalty

func (c *BeamSearchConfig) WithLengthPenalty(penalty float64) *BeamSearchConfig

WithLengthPenalty sets the length penalty factor. Values > 1.0 favor longer sequences, values < 1.0 favor shorter sequences. The penalty is applied as: score / (length ^ lengthPenalty). Default is 1.0 (no penalty).

func (*BeamSearchConfig) WithMaxLength

func (c *BeamSearchConfig) WithMaxLength(maxLen int) *BeamSearchConfig

WithMaxLength sets the maximum generation length. Generation stops when this length is reached. Default is 100.

func (*BeamSearchConfig) WithMinLength

func (c *BeamSearchConfig) WithMinLength(minLen int) *BeamSearchConfig

WithMinLength sets the minimum generation length. EOS tokens are suppressed until this length is reached. Default is 0 (no minimum).

func (*BeamSearchConfig) WithNumReturnSequences

func (c *BeamSearchConfig) WithNumReturnSequences(num int) *BeamSearchConfig

WithNumReturnSequences sets how many sequences to return. Must be <= beamSize. The top numReturnSeqs sequences by score are returned. Default is 1 (return only the best sequence).

type RNG

type RNG interface {
	RandomUniform(g *Graph, shape shapes.Shape) *Node
}

RNG is an interface for random number generation used by the sampling strategies.

The context.Context implements this interface.

type Strategy

type Strategy int

Strategy represents the different types of sampling available.

const (
	StrategyGreedy Strategy = iota
	StrategyTemperature
	StrategyTopK
	StrategyTopP
	StrategyBeamSearch // Requires specialized implementation, see sample.NewBeamSearch or simply use the decode.Decoder with StrategyBeamSearch strategy.
)

func StrategyString

func StrategyString(s string) (Strategy, error)

StrategyString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func StrategyValues

func StrategyValues() []Strategy

StrategyValues returns all values of the enum

func (Strategy) IsAStrategy

func (i Strategy) IsAStrategy() bool

IsAStrategy returns "true" if the value is listed in the enum definition. "false" otherwise

func (Strategy) MarshalJSON

func (i Strategy) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Strategy

func (Strategy) MarshalText

func (i Strategy) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface for Strategy

func (Strategy) MarshalYAML

func (i Strategy) MarshalYAML() (interface{}, error)

MarshalYAML implements a YAML Marshaler for Strategy

func (Strategy) String

func (i Strategy) String() string

func (*Strategy) UnmarshalJSON

func (i *Strategy) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Strategy

func (*Strategy) UnmarshalText

func (i *Strategy) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for Strategy

func (*Strategy) UnmarshalYAML

func (i *Strategy) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements a YAML Unmarshaler for Strategy

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL