Documentation
¶
Overview ¶
Package transformers implements the various Gema models. It is based on https://github.com/google-deepmind/gemma/blob/main/gemma/transformer.py
Index ¶
- Constants
- func ApplyRotaryPositionEncoding(operand, positions *Node, maxWaveLength int) *Node
- func Attention(ctx *context.Context, config *Config, attentionIdx int, x, positions *Node, ...) *Node
- func AttentionTypeStrings() []string
- func Block(ctx *context.Context, config *Config, attentionIdx int, x, positions *Node, ...) *Node
- func DecodeTokens(ctx *context.Context, config *Config, x *Node) *Node
- func EmbedTokens(ctx *context.Context, config *Config, currentTokens *Node) *Node
- func GatedFeedForward(ctx *context.Context, x *Node, hiddenDim int, transposeGatingEinsum bool) *Node
- func GemmaTypeStrings() []string
- func GemmaWithCache(ctx *context.Context, config *Config, currentTokens, currentPositions *Node, ...) *Node
- func HuggingFaceGatedFeedForward(ctx *context.Context, x *Node, hiddenDim int, transposeGatingEinsum bool) *Node
- func KernelEinsum(ctx *context.Context, equation string, x *Node, kernelShape shapes.Shape) *Node
- func Must(err error)
- func Must1[T any](v T, err error) T
- func QueryPreAttentionNormalisationTypeStrings() []string
- func RMSNorm(ctx *context.Context, x *Node) *Node
- func SoftCap(x *Node, cap float64) *Node
- type AttentionType
- func (i AttentionType) IsAAttentionType() bool
- func (i AttentionType) MarshalJSON() ([]byte, error)
- func (i AttentionType) MarshalText() ([]byte, error)
- func (i AttentionType) MarshalYAML() (interface{}, error)
- func (i AttentionType) String() string
- func (i *AttentionType) UnmarshalJSON(data []byte) error
- func (i *AttentionType) UnmarshalText(text []byte) error
- func (i *AttentionType) UnmarshalYAML(unmarshal func(interface{}) error) error
- func (AttentionType) Values() []string
- type Cache
- type Config
- type GemmaType
- func (i GemmaType) IsAGemmaType() bool
- func (i GemmaType) MarshalJSON() ([]byte, error)
- func (i GemmaType) MarshalText() ([]byte, error)
- func (i GemmaType) MarshalYAML() (interface{}, error)
- func (i GemmaType) String() string
- func (i *GemmaType) UnmarshalJSON(data []byte) error
- func (i *GemmaType) UnmarshalText(text []byte) error
- func (i *GemmaType) UnmarshalYAML(unmarshal func(interface{}) error) error
- func (GemmaType) Values() []string
- type QueryPreAttentionNormalisationType
- func (i QueryPreAttentionNormalisationType) IsAQueryPreAttentionNormalisationType() bool
- func (i QueryPreAttentionNormalisationType) MarshalJSON() ([]byte, error)
- func (i QueryPreAttentionNormalisationType) MarshalText() ([]byte, error)
- func (i QueryPreAttentionNormalisationType) MarshalYAML() (interface{}, error)
- func (i QueryPreAttentionNormalisationType) String() string
- func (i *QueryPreAttentionNormalisationType) UnmarshalJSON(data []byte) error
- func (i *QueryPreAttentionNormalisationType) UnmarshalText(text []byte) error
- func (i *QueryPreAttentionNormalisationType) UnmarshalYAML(unmarshal func(interface{}) error) error
- func (QueryPreAttentionNormalisationType) Values() []string
Constants ¶
const RoPEDefaultMaxWaveLength = 10_000
RoPEDefaultMaxWaveLength is a default value to use for rotary positional encoding. See ApplyRotaryPositionEncoding.
Variables ¶
This section is empty.
Functions ¶
func ApplyRotaryPositionEncoding ¶
func ApplyRotaryPositionEncoding(operand, positions *Node, maxWaveLength int) *Node
ApplyRotaryPositionEncoding (aka. RoPE) applies the positional encoding to the operand, given the positions (integer numbers of the position).
- operand: the last axis ("features" or "embedding" axis) must be divisible by 2. The shape usually is [batchSize, sequenceSize, numHeads, headDim]. - positions: its shape must be a prefix to operand. Typically, it's shaped [batchSize, sequenceSize]. - maxWaveLength: it uses wave lengths in a power scale, up to maxWaveLength -- see RoPEDefaultMaxWaveLength for a reasonable value.
Reference: https://arxiv.org/abs/2104.09864
func Attention ¶
func Attention(ctx *context.Context, config *Config, attentionIdx int, x, positions *Node, cache *trees.Tree[*Node], attentionMask *Node) *Node
Attention builds an attention layer, optionally using cache to store a limited amount of context.
- attentionIdx indexes attention configuration (in config) parameters, like config.AttentionTypes.
- x is the operand shaped [batchSize, sequenceLength, embedDim]. If using cache, typically the sequenceLength will be 1.
- positions are the positions of the sequence in x, shaped int32[batchSize, sequenceLength].
- cache: if set, x is only used for the current token (so sequenceLength will be 1), and the x's key and value projections are set in the cache. After that, cache is used instead of x for the attention.
- attentionMask: shaped bool[batchSize, sequenceLength, sequenceLength] (if cache is nil) or bool[batchSize, sequenceLength==1, config.MaxCacheLength] if cache is being used.
func AttentionTypeStrings ¶
func AttentionTypeStrings() []string
AttentionTypeStrings returns a slice of all String values of the enum
func Block ¶
func Block(ctx *context.Context, config *Config, attentionIdx int, x, positions *Node, cache *trees.Tree[*Node], attentionMask *Node) *Node
Block implements one transformer block for the Gemma model. x is shaped [batchSize, sequenceLength], and if using cache (cache != nil), x will only contain the current token, shaped [batchSize, 1].
The attentionIdx indexes attention configuration (in config) parameters, like config.AttentionTypes.
If cache is given, attentionMask is relative to the cache. Otherwise, attentionMask is relative to the operand x.
func DecodeTokens ¶
DecodeTokens use the same table as EmbedTokens to convert embedding back to the tokens -- or to token logits. Input: current embeddings: [batchSize, sequenceLength, embedDim] Output: logits for each token: [batchSize, sequenceLength, vocabularySize]
func EmbedTokens ¶
EmbedTokens using weights in Config. Input: currentTokens: [batchSize, sequenceLength] Output: embeddings: [batchSize, sequenceLength, config.EmbedDim]
func GatedFeedForward ¶
func GatedFeedForward(ctx *context.Context, x *Node, hiddenDim int, transposeGatingEinsum bool) *Node
GatedFeedForward layer for Gemma: - hiddenDim: one intermediary layer. - transposeGatingEinsum: for some versions of Gemma, the gating (hidden) weights have the axes transposed. - It uses Gelu as activation function for the gating signal (multiplied by the up-projected values).
func GemmaTypeStrings ¶
func GemmaTypeStrings() []string
GemmaTypeStrings returns a slice of all String values of the enum
func GemmaWithCache ¶
func GemmaWithCache(ctx *context.Context, config *Config, currentTokens, currentPositions *Node, cache *trees.Tree[*Node], cacheAttentionMask *Node) *Node
GemmaWithCache creates a forward path on a Gemma model for one decoding step, using the weights in Config to initialize the variables.
It takes as input the current token to decode currentTokens (shape [batchSize, 1] in a sequence along with currentPosition (shape [batchSize, 1]) and the current cache of the key/values for each transformer layer (see Cache), whose elements are generally shaped [batchSize, MaxCacheLength,...].
It updates the Cache with the new step in-place, and returns the logits (shape [batchSize, <num_tokens>]) of the prediction of the next token.
func HuggingFaceGatedFeedForward ¶
func HuggingFaceGatedFeedForward(ctx *context.Context, x *Node, hiddenDim int, transposeGatingEinsum bool) *Node
HuggingFaceGatedFeedForward layer for Gemma, the HuggingFace version, with transposed weights: - hiddenDim: one intermediary layer. - transposeGatingEinsum: for some versions of Gemma, the gating (hidden) weights have the axes transposed. - It uses Gelu as activation function for the gating signal (multiplied by the up-projected values).
func KernelEinsum ¶
KernelEinsum multiplies the input by a kernel of the given shape, using the given graph.EinSum equation.
func QueryPreAttentionNormalisationTypeStrings ¶
func QueryPreAttentionNormalisationTypeStrings() []string
QueryPreAttentionNormalisationTypeStrings returns a slice of all String values of the enum
Types ¶
type AttentionType ¶
type AttentionType int
const ( AttentionTypeUnknown AttentionType = iota AttentionTypeGlobal AttentionTypeLocalSliding )
func AttentionTypeString ¶
func AttentionTypeString(s string) (AttentionType, error)
AttentionTypeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func AttentionTypeValues ¶
func AttentionTypeValues() []AttentionType
AttentionTypeValues returns all values of the enum
func (AttentionType) IsAAttentionType ¶
func (i AttentionType) IsAAttentionType() bool
IsAAttentionType returns "true" if the value is listed in the enum definition. "false" otherwise
func (AttentionType) MarshalJSON ¶
func (i AttentionType) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface for AttentionType
func (AttentionType) MarshalText ¶
func (i AttentionType) MarshalText() ([]byte, error)
MarshalText implements the encoding.TextMarshaler interface for AttentionType
func (AttentionType) MarshalYAML ¶
func (i AttentionType) MarshalYAML() (interface{}, error)
MarshalYAML implements a YAML Marshaler for AttentionType
func (AttentionType) String ¶
func (i AttentionType) String() string
func (*AttentionType) UnmarshalJSON ¶
func (i *AttentionType) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for AttentionType
func (*AttentionType) UnmarshalText ¶
func (i *AttentionType) UnmarshalText(text []byte) error
UnmarshalText implements the encoding.TextUnmarshaler interface for AttentionType
func (*AttentionType) UnmarshalYAML ¶
func (i *AttentionType) UnmarshalYAML(unmarshal func(interface{}) error) error
UnmarshalYAML implements a YAML Unmarshaler for AttentionType
func (AttentionType) Values ¶
func (AttentionType) Values() []string
type Cache ¶
type Cache struct {
// Config of the model.
Config *Config
// BatchSize for this cache.
BatchSize int
// Length (in number of steps) of the cache. The cache itself is rotating on this size.
// It comes from config.MaxCacheLength.
Length int
// Data holds the cached data, organized as a trees.Tree[*tensors.Tensor].
Data *trees.Tree[*tensors.Tensor]
}
Cache is a state cache of a (batch of) sequence being encoded/decoded.
It has a fixed size (so typical cached values with be prefixed with the dimensions [BatchSize, Cache.Size], and current position (where each decode step is stored) is rotating: CurrentStep = (CurrentStep+1)%Cache.Length).
It's stored as a trees.Tree[*tensor.Tensor].
For the Gemma2 model, the first level of the tree being the layer names, and the second level hold the "keys" and "values" embedding caches for each transformer layer.
type Config ¶
type Config struct {
Type GemmaType
DType dtypes.DType
VocabularySize int
NumLayers, NumEmbed int
// HuggingFaceVersion has different shapes for some of the variables.
HuggingFaceVersion bool
// EmbedDim is also called "features" in the original code. It is the representation size (last dimension) of the output of the attention layers.
EmbedDim int
NumHeads, HeadDim int
HiddenDim int
NumKVHeads int
FinalLogitSoftCap float64
UseQKV, UseGroupQueryAttention bool
UsePostAttentionNorm, UsePostFFWNorm bool
AttentionTypes []AttentionType
MaxCacheLength int
QueryPreAttentionNorm QueryPreAttentionNormalisationType
// AttentionLogitsSoftCap limits the attention logits (logits = AttentionLogitsSoftCap * tanh(logits/AttentionLogitsSoftCap)).
// Enabled if > 0.
AttentionLogitsSoftCap float64
SlidingWindowSize int
TransposeGatingEinsum bool
}
Config Gemma transformer model.
func NewConfigFromContext ¶
NewConfigFromContext creates a transformers config model, based on the structure of the variables in the given context -- the scope has to be set directly to the model variables.
func (*Config) QueryPreAttentionScalar ¶
QueryPreAttentionScalar is a multiplier to the query projections.
type GemmaType ¶
type GemmaType int
func GemmaTypeString ¶
GemmaTypeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func GemmaTypeValues ¶
func GemmaTypeValues() []GemmaType
GemmaTypeValues returns all values of the enum
func (GemmaType) IsAGemmaType ¶
IsAGemmaType returns "true" if the value is listed in the enum definition. "false" otherwise
func (GemmaType) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface for GemmaType
func (GemmaType) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface for GemmaType
func (GemmaType) MarshalYAML ¶
MarshalYAML implements a YAML Marshaler for GemmaType
func (*GemmaType) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface for GemmaType
func (*GemmaType) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface for GemmaType
func (*GemmaType) UnmarshalYAML ¶
UnmarshalYAML implements a YAML Unmarshaler for GemmaType
type QueryPreAttentionNormalisationType ¶
type QueryPreAttentionNormalisationType int
QueryPreAttentionNormalisationType defines how to normalize query before attention.
const ( // QueryNormTypeByOneOverSqrtHeadDim indicates whether to scale the query by 1/sqrt(head_dim) QueryNormTypeByOneOverSqrtHeadDim QueryPreAttentionNormalisationType = iota // QueryNormTypeByEmbedDimDivNumHeads indicates whether to scale the query by `embed_dim // num_heads` QueryNormTypeByEmbedDimDivNumHeads // QueryNormTypeByOneOverSqrtEmbedDimDivNumHeads indicates whether to scale the query by `1/sqrt(embed_dim // num_heads)` QueryNormTypeByOneOverSqrtEmbedDimDivNumHeads )
func QueryPreAttentionNormalisationTypeString ¶
func QueryPreAttentionNormalisationTypeString(s string) (QueryPreAttentionNormalisationType, error)
QueryPreAttentionNormalisationTypeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func QueryPreAttentionNormalisationTypeValues ¶
func QueryPreAttentionNormalisationTypeValues() []QueryPreAttentionNormalisationType
QueryPreAttentionNormalisationTypeValues returns all values of the enum
func (QueryPreAttentionNormalisationType) IsAQueryPreAttentionNormalisationType ¶
func (i QueryPreAttentionNormalisationType) IsAQueryPreAttentionNormalisationType() bool
IsAQueryPreAttentionNormalisationType returns "true" if the value is listed in the enum definition. "false" otherwise
func (QueryPreAttentionNormalisationType) MarshalJSON ¶
func (i QueryPreAttentionNormalisationType) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface for QueryPreAttentionNormalisationType
func (QueryPreAttentionNormalisationType) MarshalText ¶
func (i QueryPreAttentionNormalisationType) MarshalText() ([]byte, error)
MarshalText implements the encoding.TextMarshaler interface for QueryPreAttentionNormalisationType
func (QueryPreAttentionNormalisationType) MarshalYAML ¶
func (i QueryPreAttentionNormalisationType) MarshalYAML() (interface{}, error)
MarshalYAML implements a YAML Marshaler for QueryPreAttentionNormalisationType
func (QueryPreAttentionNormalisationType) String ¶
func (i QueryPreAttentionNormalisationType) String() string
func (*QueryPreAttentionNormalisationType) UnmarshalJSON ¶
func (i *QueryPreAttentionNormalisationType) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for QueryPreAttentionNormalisationType
func (*QueryPreAttentionNormalisationType) UnmarshalText ¶
func (i *QueryPreAttentionNormalisationType) UnmarshalText(text []byte) error
UnmarshalText implements the encoding.TextUnmarshaler interface for QueryPreAttentionNormalisationType
func (*QueryPreAttentionNormalisationType) UnmarshalYAML ¶
func (i *QueryPreAttentionNormalisationType) UnmarshalYAML(unmarshal func(interface{}) error) error
UnmarshalYAML implements a YAML Unmarshaler for QueryPreAttentionNormalisationType
func (QueryPreAttentionNormalisationType) Values ¶
func (QueryPreAttentionNormalisationType) Values() []string