transformers

package
v0.0.0-...-83792b2 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2024 License: Apache-2.0 Imports: 14 Imported by: 1 module, 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

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

View Source
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

func DecodeTokens(ctx *context.Context, config *Config, x *Node) *Node

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

func EmbedTokens(ctx *context.Context, config *Config, currentTokens *Node) *Node

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

func KernelEinsum(ctx *context.Context, equation string, x *Node, kernelShape shapes.Shape) *Node

KernelEinsum multiplies the input by a kernel of the given shape, using the given graph.EinSum equation.

func Must

func Must(err error)

Must panics if the error is not nil.

func Must1

func Must1[T any](v T, err error) T

Must1 panics in case of error, otherwise returns the one return value.

func QueryPreAttentionNormalisationTypeStrings

func QueryPreAttentionNormalisationTypeStrings() []string

QueryPreAttentionNormalisationTypeStrings returns a slice of all String values of the enum

func RMSNorm

func RMSNorm(ctx *context.Context, x *Node) *Node

RMSNorm normalizes by its root-mean-square x = x / √(mean(sqrt(x), axis=-1) + epsilon) and applies a learned scale.

func SoftCap

func SoftCap(x *Node, cap float64) *Node

SoftCap using Tanh, so values won't go beyond +/- cap. If cap <= 0, it is a no-op.

SoftCap(x) = Tanh(x/cap) * cap

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.

func NewCache

func NewCache(config *Config, batchSize int) (*Cache, error)

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

func NewConfigFromContext(ctx *context.Context) (*Config, error)

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

func (c *Config) QueryPreAttentionScalar() float64

QueryPreAttentionScalar is a multiplier to the query projections.

type GemmaType

type GemmaType int
const (
	UnknownGemmaType GemmaType = iota
	Gemma_2B
	Gemma_7B
	Gemma2_2B
	Gemma2_9B
	Gemma2_27B
)

func GemmaTypeString

func GemmaTypeString(s string) (GemmaType, error)

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

func (i GemmaType) IsAGemmaType() bool

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

func (GemmaType) MarshalJSON

func (i GemmaType) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for GemmaType

func (GemmaType) MarshalText

func (i GemmaType) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface for GemmaType

func (GemmaType) MarshalYAML

func (i GemmaType) MarshalYAML() (interface{}, error)

MarshalYAML implements a YAML Marshaler for GemmaType

func (GemmaType) String

func (i GemmaType) String() string

func (*GemmaType) UnmarshalJSON

func (i *GemmaType) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for GemmaType

func (*GemmaType) UnmarshalText

func (i *GemmaType) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for GemmaType

func (*GemmaType) UnmarshalYAML

func (i *GemmaType) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements a YAML Unmarshaler for GemmaType

func (GemmaType) Values

func (GemmaType) Values() []string

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 (*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

Jump to

Keyboard shortcuts

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