Documentation
¶
Index ¶
- Constants
- func ArchitectureStrings() []string
- func MakeIncrementalModelFn(m *Model) decode.IncrementalModelFn
- func MakeIterativeModelFn(m *Model) decode.IterativeModelFn
- type Architecture
- type LayerType
- type Model
- func (m *Model) AllLayers(ctx *context.Context, tokens, mask *Node, useKVCache bool, position int) (lastLayer *Node, allLayers []*Node)
- func (m *Model) EmbedTokens(ctx *context.Context, tokens *Node) *Node
- func (m *Model) EmbedTokensWithType(ctx *context.Context, tokens, tokenTypes *Node) *Node
- func (m *Model) ForwardLayer(ctx *context.Context, layerNum int, x, mask *Node, useCache bool, position int) *Node
- func (m *Model) FromContext(ctx *context.Context) *Model
- func (m *Model) Logits(ctx *context.Context, tokens, mask *Node) *Node
- func (m *Model) LogitsFromEmbeddings(ctx *context.Context, embeddings *Node) *Node
- func (m *Model) LogitsWithKVCache(ctx *context.Context, newTokens *Node, position int) *Node
- func (m *Model) PrePositionalEncoder(ctx *context.Context, x *Node, position int, useKVCache bool) *Node
- func (m *Model) WithActivation(activation activations.Type) *Model
- func (m *Model) WithArchitecture(arch Architecture) *Model
- func (m *Model) WithBias(use bool) *Model
- func (m *Model) WithCausalMask(use bool) *Model
- func (m *Model) WithDType(dtype dtypes.DType) *Model
- func (m *Model) WithDropout(rate float64) *Model
- func (m *Model) WithEmbedNormalization(norm string) *Model
- func (m *Model) WithFFNDim(dim int) *Model
- func (m *Model) WithFinalNormalization(norm string) *Model
- func (m *Model) WithLayerNorm(use bool) *Modeldeprecated
- func (m *Model) WithLayerPositionalEncoder(layerNum int, encoder pos.Encoder) *Model
- func (m *Model) WithLayerTypes(layerTypes []LayerType) *Model
- func (m *Model) WithMaxPosEmbed(maxLen int) *Model
- func (m *Model) WithNormEpsilon(eps float64) *Model
- func (m *Model) WithNormalization(norm string) *Model
- func (m *Model) WithNumKVHeads(num int) *Model
- func (m *Model) WithPositionalEncoder(encoder pos.Encoder) *Model
- func (m *Model) WithRoPE(baseFreq float64) *Model
- func (m *Model) WithScalingOfTokenEmbeddings(useScaling bool) *Model
- func (m *Model) WithSlidingWindow(window int) *Model
- func (m *Model) WithTokenTypeEmbedding(vocabSize int) *Model
- func (m *Model) WithTransposedWeights(transposed bool) *Model
Constants ¶
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
func MakeIncrementalModelFn ¶ added in v0.27.3
func MakeIncrementalModelFn(m *Model) decode.IncrementalModelFn
MakeIncrementalModelFn returns a model function used by the decoder for incremental generation with KVCache, using the decode package.
func MakeIterativeModelFn ¶ added in v0.27.3
func MakeIterativeModelFn(m *Model) decode.IterativeModelFn
MakeIterativeModelFn returns a "iterative" model function for iteratively (increasing sequence length, no KVCache) generation, using the decode package.
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 LayerType ¶ added in v0.27.3
type LayerType int
LayerType represents the type of attention mechanism used in a transformer layer.
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
ScaleTokenEmbeddings bool // Whether to scale token embeddings by sqrt(m.EmbedDim).
FinalNormalization string // e.g. "layer", "rms", "batch", "none" or "" (see layers.Normalization*)
Architecture Architecture // e.g. ArchitectureStandard, ArchitectureGemma
EmbedNormalization string // e.g. "layer", "rms", "none" or ""
TokenTypeEmbedSize int // e.g. Number of token types, 2 for BERT. See WithTokenTypeEmbedding.
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
LayerTypes []LayerType // Defines the type per layer (e.g. FullAttention, SlidingAttention)
SlidingWindow int // Size of the sliding window for SlidingAttention layers
// 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
// contains filtered or unexported fields
}
Model configures a cached transformer model.
func NewFromContext ¶
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) AllLayers ¶ added in v0.27.3
func (m *Model) AllLayers(ctx *context.Context, tokens, mask *Node, useKVCache bool, position int) (lastLayer *Node, allLayers []*Node)
AllLayers takes the input tokens and creates the forward graph for the transformer model, returning the last layer and all the intermediate layers.
- tokens: shaped [batchSize, seqLen], or simply [seqLen]
- mask: optional, if provided the shape must match tokens.Shape(), and it indicates which tokens are valid (1) and which are padding (0). The attention mask (causal or not) is computed taking into consideration the mask.
- useKVCache: whether to use KV cache for the attention layers.
- position: the position of the new tokens in the sequence, only used for KV cache.
See also Logits() or LogitsFromEmbeddings()if you want to get the logits for predicting the next token.
It returns:
- lastLayer: the final hidden state of the last layer, shaped [batchSize, seqLen,hiddenSize].
- allLayers: the input to the first layer and the output of each layer. It follows the HuggingFace convention, where the allLayers[0] is the input to the first attention layer, and the following nodes in allLayers are the outputs of all NumHiddenLayers attention layers.
func (*Model) EmbedTokens ¶ added in v0.27.3
EmbedTokens returns the token embeddings for the given tokens using a lookup table. This is the very first step of the transformer model.
If you want the model embeddings after of the full model, take the last layer of AllLayers.
This step is done automatically by AllLayers or Logits, but if needed, it can be used separately by calling this method.
- tokens: shaped [batchSize, seqLen] or [seqLen]
Returns: [batchSize, seqLen, EmbedDim]. Notice if no batchSize was given, a batch axis with size of 1 is created. EmbedTokens returns the token embeddings for the given tokens using a lookup table. This is the very first step of the transformer model.
It defaults to TokenType 0 for all tokens if TokenTypeEmbedSize > 0. Use EmbedTokensWithType to select a different index.
func (*Model) EmbedTokensWithType ¶ added in v0.27.3
EmbedTokensWithType returns the token embeddings for the given tokens and tokenTypes using lookup tables.
It requires WithTokenTypeEmbedding configuration.
The tokenTypes define an extra constant embedding added to all tokens based on the "token type". For BERT models, there are two different sentences, which gets a different "token type".
tokenTypes must be a scalar int (limited to the vocabSize set in WithTokenTypeEmbedding). Or it can be nil, in which case it defaults to TokenType 0 for all tokens if TokenTypeEmbedSize > 0.
func (*Model) ForwardLayer ¶ added in v0.27.2
func (m *Model) ForwardLayer(ctx *context.Context, layerNum int, x, mask *Node, useCache bool, position int) *Node
ForwardLayer executes a single transformer layer block depending on the configured architecture.
- ctx: context must be already scoped for the layer, e.g. ctx.In("layer_0") - x: features coming from the previous layer (or token embedding table), shape [batchSize, seqLen, embedDim] - mask: (optional, can be nil) shaped [batchSize, seqLen] - useCache: if true, use KV cache -- Experimental: KVCache will change. - position: position of the first token in the sequence, used only if using KV cache, otherwise we assum 0.
It returns the output of the layer, shape [batchSize, seqLen, embedDim].
This step is done automatically by AllLayers or Logits, but if needed, it can be used separately by calling this method.
func (*Model) FromContext ¶
FromContext configures the model with optional hyperparameters from the context. This allows fine-tuning an existing model configuration.
func (*Model) Logits ¶ added in v0.27.3
Logits builds the model including the last logits projection to predict the next token, for each element of the sequence.
This form can be used to embed full sentences or for training.
- tokens: shaped [batchSize, seqLen], or simply [seqLen]
- mask: optional, if provided the shape must match tokens.Shape(), and it indicates which tokens are valid (1) and which are padding (0). The attention mask (causal or not) is computed taking into consideration the mask.
It returns the logits of the last layer, typically shaped [batchSize, seqLen, vocabSize]
func (*Model) LogitsFromEmbeddings ¶ added in v0.27.3
LogitsFromEmbeddings takes the embeddings of the last attention layer (returned by AllLayers) and computes the logits over the vocabulary size. This is the last step of the model.
This step is done automatically by Logits (which builds the full forward path from the tokens), but if needed, it can be used separately by calling this method.
func (*Model) LogitsWithKVCache ¶ added in v0.27.3
LogitsWithKVCache returns the forward path for the newTokens sequence, using the KV cache.
- newTokens: shaped [batchSize, 1] with the new tokens to be processed. - position: the position of the new tokens in the sequence, only used for KV cache.
**Experimental**: likely the KVCache will change in the future.
It returns the logits of the last layer, typically shaped [batchSize, 1, vocabSize], and updates the KVCache stored as variables in the cache.
func (*Model) PrePositionalEncoder ¶ added in v0.27.3
func (m *Model) PrePositionalEncoder(ctx *context.Context, x *Node, position int, useKVCache bool) *Node
PrePositionalEncoder applies the positional encoder to the given embeddings before the first transformer layer.
This only applies if the positional encoder implements the pos.PreEncoder interface (some positional encoders run later). Otherwise, or if the encoder is nil, it simply returns x.
This step is done automatically by AllLayers or Logits, but if needed, it can be used separately by calling this method.
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) WithCausalMask ¶ added in v0.27.2
WithCausalMask toggles causal masking.
func (*Model) WithDropout ¶
WithDropout sets dropout rate.
func (*Model) WithEmbedNormalization ¶ added in v0.27.3
WithEmbedNormalization sets the normalization type ("layer", "rms", "none" or "") to be applied only once after the token embeddings and before the first transformer layer.
func (*Model) WithFFNDim ¶
WithFFNDim sets FFN dimension.
func (*Model) WithFinalNormalization ¶ added in v0.27.3
WithFinalNormalization toggles the final normalization after all attention layers. The values "none" or "" mean no final normalization.
func (*Model) WithLayerNorm
deprecated
func (*Model) WithLayerPositionalEncoder ¶ added in v0.27.3
WithLayerPositionalEncoder sets the positional encoder for a specific layer.
func (*Model) WithLayerTypes ¶ added in v0.27.3
WithLayerTypes sets the layer types (FullAttention, SlidingAttention) for each layer.
func (*Model) WithMaxPosEmbed ¶
WithMaxPosEmbed sets max positional embedding length.
func (*Model) WithNormEpsilon ¶ added in v0.27.2
WithNormEpsilon sets the epsilon value used for normalization layers.
func (*Model) WithNormalization ¶ added in v0.27.2
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
WithNumKVHeads enables Grouped Query Attention (GQA) if different from NumHeads.
func (*Model) WithPositionalEncoder ¶ added in v0.27.3
WithPositionalEncoder sets the default positional encoder.
func (*Model) WithScalingOfTokenEmbeddings ¶ added in v0.27.3
WithScalingOfTokenEmbeddings configuration method configures whether to scale token embeddings by the square root of the embedding dimension. If true, it multiplies the token embeddings by math.Sqrt(m.EmbedDim). Some models (like Gemma and Llama) use this scaling factor.
func (*Model) WithSlidingWindow ¶ added in v0.27.3
WithSlidingWindow sets the sliding window size for local attention layers. This is applied for all layers of type SlidingAttention.
func (*Model) WithTokenTypeEmbedding ¶ added in v0.27.3
WithTokenTypeEmbedding an extra constant embedding based on the "token type".
In BERT models it is the sentence id, when classifying two sentences, and the vocabSize defaults to 2.
The EmbedTokens will default to use the TokenType 0 (the default), but you can use EmbedTokensWithType to select a different index.
func (*Model) WithTransposedWeights ¶ added in v0.27.2
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.