decode

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: 9 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

Index

Constants

View Source
const (
	ParamMaxLength   = "decode_max_length"
	ParamStrategy    = "decode_strategy"
	ParamTemperature = "decode_temperature"
	ParamTopK        = "decode_top_k"
	ParamTopP        = "decode_top_p"
	ParamBeamSize    = "decode_beam_size"
	ParamEosTokenId  = "decode_eos_token_id"
	ParamStopOnEOS   = "decode_stop_on_eos"
)

Hyperparameter keys for context configuration

Variables

This section is empty.

Functions

This section is empty.

Types

type Decoder

type Decoder struct {
	// Model functions (exactly one should be set)
	ModelFn            IterativeModelFn   // Standard model for non-cached generation
	IncrementalModelFn IncrementalModelFn // Incremental model for KV-cached generation

	// Generation parameters
	MaxLength   int
	Strategy    sample.Strategy
	Temperature float32
	TopK        int
	TopP        float32
	BeamSize    int
	EosTokenId  int
	StopOnEOS   bool
	// contains filtered or unexported fields
}

Decoder configures and executes autoregressive text generation. Supports multiple sampling strategies (greedy, temperature, top-k, nucleus, beam search) and incremeantal models, usually using some form of cache (e.g.: a "KV-cache").

func New

func New[M interface {
	IterativeModelFn | IncrementalModelFn
}](modelFn M) *Decoder

New creates a decoder for autoregressive text generation. Accepts either ModelFn (non-cached, full sequence) or IncrementalModelFn (KV-cached). The decoder automatically detects which type is provided and configures itself accordingly.

Parameters:

  • modelFn: Either ModelFn for full-sequence processing or IncrementalModelFn for cached generation

Returns:

  • Decoder with default generation parameters (greedy sampling, maxLength=100)

Example:

decoder := decode.New(model.Incremental()).
	WithStrategy(sample.StrategyTemperature).WithTemperature(0.8)
output, err := decoder.Decode(prompt)

func (*Decoder) Decode

func (dec *Decoder) Decode(
	backend backends.Backend,
	ctx *context.Context,
	prompt any,
) (*tensors.Tensor, error)

Decode performs autoregressive text generation from a prompt. The prompt can be 1D [seqLen] or 2D [batch, seqLen] tensor of token IDs.

Parameters:

  • backend: Backend for computation
  • ctx: Context containing model parameters
  • prompt: Input token sequence (1D or 2D tensor)

Returns:

  • Generated token sequence including the prompt
  • Error if generation fails or configuration is invalid

Example:

prompt := []int32{1, 2, 3}  // Token IDs
output, err := decoder.Decode(backend, ctx, prompt)

func (*Decoder) FromContext

func (dec *Decoder) FromContext(ctx *context.Context) *Decoder

FromContext configures the decoder with hyperparameters from the context. This allows fine-tuning an existing decoder configuration.

Supported hyperparameters:

  • decode_max_length: Maximum generation length (default: unchanged)
  • decode_strategy: Sampling strategy ("greedy", "temperature", "top_k", "top_p", "beam_search")
  • decode_temperature: Temperature for sampling (default: unchanged)
  • decode_top_k: k for top-k sampling (default: unchanged)
  • decode_top_p: p for nucleus sampling (default: unchanged)
  • decode_beam_size: Beam size for beam search (default: unchanged)
  • decode_eos_token_id: End-of-sequence token ID (default: unchanged)
  • decode_stop_on_eos: Whether to stop on EOS (default: unchanged)

Example:

ctx.SetParams(map[string]any{
    "decode_strategy": "temperature",
    "decode_temperature": 0.8,
    "decode_max_length": 200,
})
decoder.FromContext(ctx)

func (*Decoder) GenerateStreaming

func (dec *Decoder) GenerateStreaming(
	backend backends.Backend,
	ctx *context.Context,
	prompt any,
	callback func(token int) bool,
) error

GenerateStreaming performs streaming generation, yielding tokens as they are generated. The callback function is called for each generated token and can return false to stop generation.

Parameters:

  • backend: Backend for computation
  • ctx: Context containing model parameters
  • prompt: Input token sequence (1D or 2D tensor)
  • callback: Function called with each generated token ID; return false to stop

Returns:

  • Error if generation fails

Note: This is a placeholder for future streaming support.

func (*Decoder) WithBeamSize

func (dec *Decoder) WithBeamSize(beamSize int) *Decoder

WithBeamSize sets the beam size for beam search. Higher values explore more candidates but are slower.

func (*Decoder) WithEOS

func (dec *Decoder) WithEOS(eosTokenId int) *Decoder

WithEOS sets the end-of-sequence token ID and enables early stopping. Generation stops when this token is produced.

func (*Decoder) WithMaxLength

func (dec *Decoder) WithMaxLength(maxLength int) *Decoder

WithMaxLength sets the maximum generation length (including prompt).

func (*Decoder) WithStrategy

func (dec *Decoder) WithStrategy(strategy sample.Strategy) *Decoder

WithStrategy sets the sampling strategy. The default strategy is sample.StrategyGreedy, which always take the immediately most likely next token.

func (*Decoder) WithTemperature

func (dec *Decoder) WithTemperature(temperature float32) *Decoder

WithTemperature sets the temperature for sampling. Higher values (>1.0) increase randomness, lower values (<1.0) make output more deterministic.

You have to also set the strategy to sample.StrategyTemperature or sample.StrategyTopK or sample.StrategyTopP to use this parameter

func (*Decoder) WithTopK

func (dec *Decoder) WithTopK(topK int) *Decoder

WithTopK sets k for top-k sampling. Only the k most likely tokens are considered at each step.

func (*Decoder) WithTopP

func (dec *Decoder) WithTopP(topP float32) *Decoder

WithTopP sets p for nucleus sampling. Tokens with cumulative probability up to p are considered.

type IncrementalModelFn

type IncrementalModelFn func(ctx *context.Context, newTokens *Node, position int) *Node

IncrementalModelFn represents an incremental model function, which is expected to have some form of caching (stored in the variables in the context).

It processes new tokens at a specific position, presumably reusing cached previous results (typically in the form of a "KVCache" or cached key/value projections, stored in the context).

Currently, it doesn't support concurrent generation -- it's expected to have only one cache during execution.

Parameters:

  • ctx: Model context passed along by the Decoder. Likely contains the cache during the execution.
  • newTokens: New tokens to process [batch, newLen]
  • position: Position in the sequence (for cache indexing)

Returns:

  • logits: Output logits [batch, newLen, vocabSize]

type IterativeModelFn

type IterativeModelFn func(ctx *context.Context, tokens *Node) *Node

IterativeModelFn represents a full-sequence model function, that is used iteratively during decoding, by re-feeding the whole previous state.

Only use this if your backend supports dynamic shapes, otherwise this will likely be very slow.

Parameters:

  • ctx: Model context passed along by the Decoder.
  • tokens: Input token sequence, shaped [batch, seqLen].

Returns:

  • logits: Output logits per candidate token (vocabSize), shaped [batch, seqLen, vocabSize]

Directories

Path Synopsis
Package sample provides various sampling strategies for autoregressive generation.
Package sample provides various sampling strategies for autoregressive generation.

Jump to

Keyboard shortcuts

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