transformer

package
v0.27.2 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2026 License: Apache-2.0 Imports: 12 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 (
	ParamVocabSize   = "transformer_vocab_size"
	ParamEmbedDim    = "transformer_embed_dim"
	ParamNumLayers   = "transformer_num_layers"
	ParamNumHeads    = "transformer_num_heads"
	ParamHeadDim     = "transformer_head_dim"
	ParamFFNDim      = "transformer_ffn_dim"
	ParamMaxPosEmbed = "transformer_max_pos_embed"
	ParamDType       = "transformer_dtype"
	ParamDropout     = "transformer_dropout"

	// ParamUseLayerNorm
	// Deprecated: use ParamNormalization instead.
	ParamUseLayerNorm = "transformer_use_layer_norm"

	ParamUseBias       = "transformer_use_bias"
	ParamArchitecture  = "transformer_architecture"
	ParamNormalization = "transformer_normalization"
	ParamNormEpsilon   = "transformer_norm_epsilon"
	ParamActivation    = "transformer_activation"
	ParamNumKVHeads    = "transformer_num_kv_heads"

	// Legacy RoPE parameters, used to configure PosEmbed if set.
	ParamUseRoPE       = "transformer_use_rope"
	ParamRoPEBaseFreq  = "transformer_rope_base_freq"
	ParamUseCausalMask = "transformer_use_causal_mask"
)

Hyperparameter keys for context configuration

Variables

This section is empty.

Functions

func ArchitectureStrings added in v0.27.2

func ArchitectureStrings() []string

ArchitectureStrings returns a slice of all String values of the enum

Types

type Architecture added in v0.27.2

type Architecture int

Model holds configuration for building a cached transformer model. Architecture is an enum for the supported transformer architectures.

It is converted to and from string by using the generated ArchitectureString function.

const (
	ArchitectureStandard Architecture = iota
	ArchitectureGemma
	ArchitectureGemma3
)

func ArchitectureString added in v0.27.2

func ArchitectureString(s string) (Architecture, error)

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

func ArchitectureValues added in v0.27.2

func ArchitectureValues() []Architecture

ArchitectureValues returns all values of the enum

func (Architecture) IsAArchitecture added in v0.27.2

func (i Architecture) IsAArchitecture() bool

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

func (Architecture) String added in v0.27.2

func (i Architecture) String() string

type Model

type Model struct {
	VocabSize     int              // Vocabulary size
	EmbedDim      int              // Embedding dimension
	NumLayers     int              // Transformer layers
	NumHeads      int              // Attention heads per layer
	HeadDim       int              // Head dimension
	FFNDim        int              // Feed-forward hidden dimension
	MaxPosEmbed   int              // Max positional embedding length
	DType         dtypes.DType     // Data type
	Dropout       float64          // Dropout rate (0.0 = none)
	UseBias       bool             // Use bias in dense layers
	UseCausalMask bool             // Use causal masking in attention layers
	Architecture  Architecture     // e.g. ArchitectureStandard, ArchitectureGemma
	Normalization string           // e.g. "layer", "rms", "batch", "none" or "" (see layers.Normalization*)
	NormEpsilon   float64          // Epsilon for normalization
	Activation    activations.Type // e.g. "gelu", "silu", "gelu_approximate"
	NumKVHeads    int              // For Grouped Query Attention (GQA), 0 means equal to NumHeads

	PosEmbed pos.Encoder // Positional encoder (e.g. RoPE). If nil, standard absolute positional embeddings are used.

	// TransposedProjections indicates whether to assume linear weights are transposed (as [out_features, in_features]),
	// which is standard for PyTorch nn.Linear. This enables dropping in PyTorch models directly.
	TransposedProjections bool
}

Model configures a cached transformer model.

func New

func New(vocabSize, embedDim, numLayers, numHeads, headDim int) *Model

New creates a default transformer configuration.

func NewFromContext

func NewFromContext(ctx *context.Context) *Model

NewFromContext creates a transformer model configured from context hyperparameters. It reads parameters with the following keys (with defaults):

  • transformer_vocab_size (required, no default)
  • transformer_embed_dim (required, no default)
  • transformer_num_layers (required, no default)
  • transformer_num_heads (required, no default)
  • transformer_head_dim (required, no default)
  • transformer_ffn_dim (default: embed_dim * 4)
  • transformer_max_pos_embed (default: 512)
  • transformer_dtype (default: "float32")
  • transformer_dropout (default: 0.0)
  • transformer_use_rope (default: false)
  • transformer_rope_base_freq (default: 10000.0)
  • transformer_use_layer_norm (default: true)
  • transformer_use_bias (default: true)

Example usage:

ctx.SetParams(map[string]any{
    "transformer_vocab_size": 50257,
    "transformer_embed_dim": 768,
    "transformer_num_layers": 12,
    "transformer_num_heads": 12,
    "transformer_head_dim": 64,
})
model := transformer.NewFromContext(ctx)

func (*Model) ForGeneration

func (m *Model) ForGeneration() decode.IncrementalModelFn

ForGeneration returns a model function for generation (incremental forward with KV cache).

func (*Model) ForTraining

func (m *Model) ForTraining() decode.IterativeModelFn

ForTraining returns a model function for training (full-sequence forward, no KV cache).

func (*Model) ForwardLayer added in v0.27.2

func (m *Model) ForwardLayer(ctx *context.Context, x *Node, layerIdx int, useCache bool, position int) *Node

ForwardLayer executes a single transformer layer block depending on the configured architecture.

func (*Model) FromContext

func (m *Model) FromContext(ctx *context.Context) *Model

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

func (*Model) WithActivation added in v0.27.2

func (m *Model) WithActivation(activation activations.Type) *Model

WithActivation sets the activation function type.

func (*Model) WithArchitecture added in v0.27.2

func (m *Model) WithArchitecture(arch Architecture) *Model

WithArchitecture sets the architectural style.

func (*Model) WithBias

func (m *Model) WithBias(use bool) *Model

WithBias toggles dense bias.

func (*Model) WithCausalMask added in v0.27.2

func (m *Model) WithCausalMask(use bool) *Model

WithCausalMask toggles causal masking.

func (*Model) WithDType

func (m *Model) WithDType(dtype dtypes.DType) *Model

WithDType sets data type.

func (*Model) WithDropout

func (m *Model) WithDropout(rate float64) *Model

WithDropout sets dropout rate.

func (*Model) WithFFNDim

func (m *Model) WithFFNDim(dim int) *Model

WithFFNDim sets FFN dimension.

func (*Model) WithLayerNorm deprecated

func (m *Model) WithLayerNorm(use bool) *Model

WithLayerNorm toggles layer normalization.

Deprecated: use WithNormalization("layer"), WithNormalization("none") or some other value instead.

func (*Model) WithMaxPosEmbed

func (m *Model) WithMaxPosEmbed(maxLen int) *Model

WithMaxPosEmbed sets max positional embedding length.

func (*Model) WithNormEpsilon added in v0.27.2

func (m *Model) WithNormEpsilon(eps float64) *Model

WithNormEpsilon sets the epsilon value used for normalization layers.

func (*Model) WithNormalization added in v0.27.2

func (m *Model) WithNormalization(norm string) *Model

WithNormalization sets the normalization type ("layer", "rms", "batch", "none" or "").

The values "none" or "" mean no normalization.

See constants layers.NormalizationLayerNorm ("layer"), layers.NormalizationRMSNorm ("rms"), layers.NormalizationBatchNorm ("batch") and layers.NormalizationNone ("none").

func (*Model) WithNumKVHeads added in v0.27.2

func (m *Model) WithNumKVHeads(num int) *Model

WithNumKVHeads enables Grouped Query Attention (GQA) if different from NumHeads.

func (*Model) WithPositionalEmbedding

func (m *Model) WithPositionalEmbedding(encoder pos.Encoder) *Model

WithPositionalEmbedding sets the positional encoder.

func (*Model) WithRoPE

func (m *Model) WithRoPE(baseFreq float64) *Model

WithRoPE enables RoPE with base frequency.

func (*Model) WithTransposedWeights added in v0.27.2

func (m *Model) WithTransposedWeights(transposed bool) *Model

WithTransposedWeights configures the model to assume linear weights are transposed (as [out_features, in_features]), which is the format used by PyTorch nn.Linear. This enables loading PyTorch models directly.

Jump to

Keyboard shortcuts

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