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 ¶
- func Greedy(logits *Node) *Node
- func SampleWithStrategy(ctx RNG, logits *graph.Node, strategy Strategy, temperature float64, topK int, ...) *graph.Node
- func StrategyStrings() []string
- func Temperature(rng RNG, logits *Node, temperature float64) *Node
- func TopKWithTemperature(rng RNG, logits *graph.Node, k int, temperature float64) *graph.Node
- func TopP(rng RNG, logits *Node, p float64, temperature float64) *Node
- type BeamSearchConfig
- func (c *BeamSearchConfig) EarlyStopping() bool
- func (c *BeamSearchConfig) SelectBest(sequences *Node, scores *Node) (bestSequences, bestScores *Node)
- func (c *BeamSearchConfig) Step(logits *Node, currentSequences *Node, beamScores *Node, currentLength int) (nextSequences, nextBeamScores, isFinished *Node)
- func (c *BeamSearchConfig) WithEarlyStopping(early bool) *BeamSearchConfig
- func (c *BeamSearchConfig) WithLengthPenalty(penalty float64) *BeamSearchConfig
- func (c *BeamSearchConfig) WithMaxLength(maxLen int) *BeamSearchConfig
- func (c *BeamSearchConfig) WithMinLength(minLen int) *BeamSearchConfig
- func (c *BeamSearchConfig) WithNumReturnSequences(num int) *BeamSearchConfig
- type RNG
- type Strategy
- func (i Strategy) IsAStrategy() bool
- func (i Strategy) MarshalJSON() ([]byte, error)
- func (i Strategy) MarshalText() ([]byte, error)
- func (i Strategy) MarshalYAML() (interface{}, error)
- func (i Strategy) String() string
- func (i *Strategy) UnmarshalJSON(data []byte) error
- func (i *Strategy) UnmarshalText(text []byte) error
- func (i *Strategy) UnmarshalYAML(unmarshal func(interface{}) error) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
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 ¶
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 ¶
TopKWithTemperature: mask non-top-k to -inf, then temperature.
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:
- Converts logits to log probabilities
- Suppresses EOS tokens if below minLength
- Adds current beam scores to get cumulative scores
- Selects top beamSize candidates across all beams
- 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 ¶
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.
func StrategyString ¶
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 ¶
IsAStrategy returns "true" if the value is listed in the enum definition. "false" otherwise
func (Strategy) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface for Strategy
func (Strategy) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface for Strategy
func (Strategy) MarshalYAML ¶
MarshalYAML implements a YAML Marshaler for Strategy
func (*Strategy) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface for Strategy
func (*Strategy) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface for Strategy
func (*Strategy) UnmarshalYAML ¶
UnmarshalYAML implements a YAML Unmarshaler for Strategy