attention

package
v0.28.21 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 18 Imported by: 6 modules, 5 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 attention implements multi-head attention and related utilities.

The multi-head attention implements one attention layer, as described in the paper "Attention Is All You Need" (https://arxiv.org/abs/1706.03762), with some of the modern extensions.

See MultiHeadAttention to create a builder for the the attention layer.

Index

Constants

View Source
const (
	// LayoutBHSD is the [batch, heads, seq, dim] layout.
	LayoutBHSD = compute.AttentionAxesLayoutBHSD

	// LayoutBSHD is the [batch, seq, heads, dim] layout.
	LayoutBSHD = compute.AttentionAxesLayoutBSHD
)

Variables

This section is empty.

Functions

func Core

func Core(query, key, value *Node, layout AxesLayout, options CoreOptions) (output, coefficients *Node)

Core computes the core scaled dot-product attention operation. This is the shared implementation used by MultiHeadAttention and ONNX op converters.

The layout parameter determines the axis ordering of the input tensors:

  • LayoutBHSD: [batch, heads, seq, dim] (PyTorch/ONNX convention)
  • LayoutBSHD: [batch, seq, heads, dim] (MHA convention)

Grouped Query Attention (GQA) is supported: key and value may have fewer heads than query. The number of query heads must be divisible by the number of key/value heads. Each group of query heads shares the same key/value head. This also covers Multi-Query Attention (MQA) where numKVHeads=1.

Returns:

  • output: same shape as query.
  • coefficients: attention coefficients (nil when WantCoefficients is false) shaped [batch, heads, q_seq, kv_seq] for LayoutBHSD or [batch, q_seq, heads, kv_seq] for LayoutBSHD.

func LayerTypeStrings

func LayerTypeStrings() []string

LayerTypeStrings returns a slice of all String values of the enum

func QKVProjection

func QKVProjection(x, wQKV, biasQ, biasK, biasV *Node, queryDim, keyValueDim int) (query, key, value *Node)

QKVProjection performs a fused Query-Key-Value projection: a single large matmul followed by split into separate query, key, value outputs with optional per-projection bias.

x: [..., inFeatures] wQKV: [inFeatures, queryDim+2*keyValueDim] with Q, K, V weights concatenated along the last axis biasQ, biasK, biasV: optional biases (nil for no bias) queryDim: output dimension for query projection keyValueDim: output dimension for key and value projections

If the backend supports the fused attention QKV projection, the optimized native implementation is used; otherwise the operation is decomposed into primitives. Fallback is handled automatically via InternalFusedOpCallerMulti.

func QKVProjectionDecomposed

func QKVProjectionDecomposed(x, wQKV, biasQ, biasK, biasV *Node, queryDim, keyValueDim int) []*Node

QKVProjectionDecomposed implements Query-Key-Value projection using primitive ops.

Internal: normal users will want to use MultiHeadAttention instead. This is mostly used for converting existing models (that already have fused operations like this).

x: [..., inFeatures] wQKV: [inFeatures, queryDim+2*keyValueDim] with Q, K, V weights concatenated along the last axis biasQ: [queryDim] (optional, nil for no bias) biasK: [keyValueDim] (optional, nil for no bias) biasV: [keyValueDim] (optional, nil for no bias)

Returns: [query, key, value] where query=[..., queryDim], key=[..., keyValueDim], value=[..., keyValueDim]

Types

type AxesLayout

type AxesLayout = compute.AttentionAxesLayout

AxesLayout is a type alias for compute.AttentionAxesLayout, re-exported for convenience.

type CoreOptions

type CoreOptions struct {
	// Scale is the scaling factor for attention scores. Typically 1/sqrt(head_dim).
	// If left as 0, it defaults to 1/sqrt(head_dim), where head_dim is the last dimension of query (head dimension).
	Scale float64

	// AttentionMask controls which positions can be attended to:
	//   - Boolean mask (DType.IsBoolean()): uses MaskedSoftmax — true means attend, false means ignore.
	//     This avoids the -1e9 additive trick which causes gradient and low-precision issues.
	//   - Float mask: added to scores before softmax (additive mask).
	//
	// The attentionMask must be broadcastable to the score tensor layout (using numHeads, not numKVHeads):
	//   - LayoutBHSD: broadcastable to [batch, numHeads, q_seq, kv_seq]
	//   - LayoutBSHD: broadcastable to [batch, q_seq, numHeads, kv_seq]
	//
	// The useCausalMask and mask parameters are mutually exclusive: providing both will panic.
	// If you need both causal masking and an explicit mask, combine them into a single mask
	// before calling Core (e.g. LogicalAnd a lower-triangular boolean mask with your mask).
	AttentionMask *Node

	// UseCausalMask controls whether to apply a causal (lower-triangular) mask.
	// It is mutually exclusive with AttentionMask.
	UseCausalMask bool

	// QuerySeqLen, KVSeqLen are an optional per-batch actual sequence length (int32 [B] node) for query
	// and Key/Value padding masking.
	// On the fused path, it is forwarded via the seqlen config.
	// On the decomposed path, it is materialized into a boolean padding mask.
	// Mutually exclusive with a non-nil AttentionMask.
	// If one is set the other must also be set.
	QuerySeqLen, KVSeqLen *Node

	// AttentionBias is an optional additive attention-score bias [batch, numHeads, q_seq, kv_seq]
	// (ALiBi / relative-position), added to the scores before softmax. It is DISTINCT from the
	// Q/K/V projection bias (UseProjectionBias on the builder) and from AttentionMask. It may
	// combine with UseCausalMask.
	//
	// The dtype should match those of the query/key/value.
	AttentionBias *Node

	// WantCoefficients, when true, forces the decomposed path to be used for the entire computation
	// (no fused op) and returns coefficients. When false, the fused op is attempted for
	// the output and coefficients is nil.
	WantCoefficients bool

	// ScoreSoftCap controls whether to cap the scores (of the attention softmax) using the [nn.SoftCap].
	// A value > 0 enables this feature.
	ScoreSoftCap float64

	// Scope provides the training/inference scope of the attention operation.
	// Currently, this is only needed for RNG state for dropout.
	// If not using dropout, just leave it at nil.
	Scope *model.Scope

	// DropoutRate (if not nil) applies dropout to the attention coefficients during training.
	// When dropout is active, the fused path is skipped (fused ops don't support dropout).
	// Notice: Dropout is rarely used in modern transformer models, and it prevents fusion (flash attention).
	// See discussion:
	// https://www.reddit.com/r/LocalLLaMA/comments/1pntkme/day_8_21_days_of_building_a_small_language_model/
	//
	// If using DropoutRate set also the Scope field.
	DropoutRate *Node

	// DisableFusion disables attempting to use the fused attention op (like flash-attention) when available.
	// This is mostly used for testing -- most of the times one wants fusion if available.
	DisableFusion bool
}

CoreOptions packs all the optional parameters for Core. Default values (zero values) are sensible defaults.

func (CoreOptions) String

func (o CoreOptions) String() string

String returns a representation of non-zero fields of CoreOptions.

type LayerType

type LayerType int

LayerType defines whether a layer is local (sliding window) or global.

const (
	// GlobalLayer uses full sequence attention.
	GlobalLayer LayerType = iota
	// LocalLayer uses sliding window attention.
	LocalLayer
)

func LayerTypeString

func LayerTypeString(s string) (LayerType, error)

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

func LayerTypeValues

func LayerTypeValues() []LayerType

LayerTypeValues returns all values of the enum

func (LayerType) IsALayerType

func (i LayerType) IsALayerType() bool

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

func (LayerType) String

func (i LayerType) String() string

type MultiHeadAttentionBuilder

type MultiHeadAttentionBuilder struct {
	// contains filtered or unexported fields
}

MultiHeadAttentionBuilder is a helper to build a multi-head-attention computation. Create it with MultiHeadAttention, set the desired parameters, and when all is set, call Done.

func MultiHeadAttention

func MultiHeadAttention(scope *model.Scope, query, key, value *Node, numHeads int, headDim int) *MultiHeadAttentionBuilder

MultiHeadAttention defines a multi-head attention layers, as described in [1], plus some modern extensions.

It takes query, key, and value and project them numHead times, to a headDim sized embeddings. Then it uses the dot-product of query and key as weights, and returns a softmax sum of value, for each head.

Typical shapes:

- query: `[batch_size, <query_elements>, inputQueryDim]`. - key: `[batch_size, <num_key/value_elements>, inputKeyDim]`. - value: `[batch_size, <num_key/value_elements>, inputValueDim]`.

It returns a builder object that can be further configured. When finished configuring, call MultiHeadAttentionBuilder.Done to get the output, a node of shape `[batch_size, <num_queries>, inputValueDim]`.

Notice it's common to use key=values, and even query=keys=values. For instance for encoding text, one may use the input sequence as all 3 (query, key and value).

The function returns a MultiHeadAttentionBuilder that can be further configured, and the resulting Node is returned when MultiHeadAttentionBuilder.Done is called. Alternatively one can call MultiHeadAttentionBuilder.DoneWithCoefficients, in which case it returns both the updated state and the attention coefficients.

Example:

positionEncoder := pos.NewRoPE(10000.0)
for layer := range numLayers {
	scope := scope.In("layer_%d", layer)
	// Use x for the source of query/key/values (self-attention).
	x := attention.MultiHeadAttention(scope, x, x, x, numHeads, headDim).
	    WithPositionalEncoder(positionEncoder)
	logits := attention.Done()
	...  // normalization, residual connection, etc.
}

[1] "Attention Is All You Need", https://arxiv.org/abs/1706.03762, by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin.

func SelfAttention

func SelfAttention(scope *model.Scope, x *Node, numHeads int, headDim int) *MultiHeadAttentionBuilder

SelfAttention is a convenience wrapper for MultiHeadAttention where query, key, and value are all the same tensor (self-attention).

This is equivalent to calling MultiHeadAttention(scope, x, x, x, numHeads, headDim). Returns a builder that can be further configured with methods like WithKVCache, WithRoPE, UseCausalMask, etc.

Example usage for training:

output := attention.SelfAttention(scope, x, numHeads, headDim).
    UseCausalMask().
    Dropout(0.1).
    Done()

func (*MultiHeadAttentionBuilder) Done

func (b *MultiHeadAttentionBuilder) Done() (output *Node)

Done should be called after all optional settings are configured. It returns the attention output shaped `[batch_size, <query_elements>, output_dim]`, where `output_dim` can be configured by `SetOutputDim`. Use DoneWithCoefficients if the attention coefficients are also needed.

func (*MultiHeadAttentionBuilder) DoneWithCoefficients

func (b *MultiHeadAttentionBuilder) DoneWithCoefficients() (attentionOutput, attentionCoefficients *Node)

DoneWithCoefficients or Done should be called after all optional settings are configured. It returns both the attention output and the attention coefficients (matrix) used.

Because coefficients are requested, the decomposed attention path is used (no fused SDPA op) so that the coefficient matrix is available. This may make the graph run significantly slower in some cases. Use Done instead when coefficients are not needed to allow the fused path.

`output` will be shaped `[batch_size, <query_elements>, output_dim]`, where `output_dim` can be configured by `SetOutputDim`.

`coefficients` is shaped `[batch_size, <query_elements>, <num_heads>, <key_elements>]` with the attention weights (from 0 to 1).

func (*MultiHeadAttentionBuilder) UseProjectionBias

func (b *MultiHeadAttentionBuilder) UseProjectionBias(useProjectionBias bool) *MultiHeadAttentionBuilder

UseProjectionBias defines whether to use a bias term on the final output projection. Default is true.

func (*MultiHeadAttentionBuilder) UseQKVProjection

UseQKVProjection replaces the three separate Dense projections for query, key, and value with a single fused QKVProjection (one large matmul followed by split).

This is only valid for self-attention where query, key, and value are the same node. Use SelfAttention() or pass the same node for all three to MultiHeadAttention().

The fused weight is stored under the "qkv" scope scope. This uses different variable names than the default separate projections (query/dense, key/dense, value/dense), so existing checkpoints using separate projections are not compatible.

func (*MultiHeadAttentionBuilder) UseTransposedWeights

func (b *MultiHeadAttentionBuilder) UseTransposedWeights(transposed bool) *MultiHeadAttentionBuilder

UseTransposedWeights configures the builder to assume the query, key, value, and output projection weights are stored transposed (as [out_features, in_features]).

func (*MultiHeadAttentionBuilder) WithAttentionBias

func (b *MultiHeadAttentionBuilder) WithAttentionBias(bias *Node) *MultiHeadAttentionBuilder

WithAttentionBias supplies an additive attention-score bias [B,H,Sq,Skv] (ALiBi / relative-position), threaded to CoreOptions.AttentionBias. It is DISTINCT from UseProjectionBias (the Q/K/V dense bias). The default is nil, which disables it.

func (*MultiHeadAttentionBuilder) WithCausalMask

func (b *MultiHeadAttentionBuilder) WithCausalMask(useCausalMask bool) *MultiHeadAttentionBuilder

WithCausalMask adds a mask where a query can only attend to keys with lower indices than itself. It assumes that query and key are either the same or have the same inner shape, and there is only one inner rank -- so key/query should have rank-3 shape `[batch, inner_dim, key/query_dim]`.

WithCausalMask is mutually exclusive with WithKeyMask, WithQueryMask, and WithQueryKeyMatrixMask. If you need both causal masking and an explicit mask, combine them into a single mask before passing it (e.g. LogicalAnd a lower-triangular boolean mask with your mask).

func (*MultiHeadAttentionBuilder) WithDropout

func (b *MultiHeadAttentionBuilder) WithDropout(rate *Node) *MultiHeadAttentionBuilder

WithDropout defines how much dropout to use in the attention coefficients calculation.

If set to nil to disable it (the default). Values <= 0 are a no-op, and values > 1 are invalid.

The dropout rate is a *Node, since it can be set dynamically if needed.

Notice: Dropout is rarely used in modern transformer models, and it prevents fusion (flash attention). See discussion: https://www.reddit.com/r/LocalLLaMA/comments/1pntkme/day_8_21_days_of_building_a_small_language_model/

func (*MultiHeadAttentionBuilder) WithFusion

WithFusion controls whether the backend fused scaled-dot-product-attention path may be used. Default is true. When false, Core always takes the decomposed path (useful for debugging or for configs the fused kernel does not support). GOMLX_FUSION is a separate global override.

func (*MultiHeadAttentionBuilder) WithKeyMask

func (b *MultiHeadAttentionBuilder) WithKeyMask(keyMask *Node) *MultiHeadAttentionBuilder

WithKeyMask sets a mask for keys that are actually valid and can be attended.

It defaults to no mask, meaning all keys are accessible. See also WithQueryMask.

Shape should be `[batch_size, numHeads, <key_elements>]`, or `[batch_size, <key_elements>]` if the mask is the same for every head.

Either use WithKeyMask and WithQueryMask separately or use WithKeyQueryMatrixMask, but not both. Optionally, one can also WithCausalMask, which is combined (logical-and) to any given mask.

func (*MultiHeadAttentionBuilder) WithKeyQueryDim

func (b *MultiHeadAttentionBuilder) WithKeyQueryDim(keyQueryDim int) *MultiHeadAttentionBuilder

WithKeyQueryDim allows finer configuration on the dimension of the projection used for the query/key pairs for each head. It defaults to the value given by `headDim`.

func (*MultiHeadAttentionBuilder) WithMask

func (b *MultiHeadAttentionBuilder) WithMask(mask *Node) *MultiHeadAttentionBuilder

WithMask is a simple shortcut to call WithKeyMask and WithQueryMask. Typically, it's used to handle padding in the input sequences, and can be combined with WithCausalMask.

Do not use it with KVCache.

func (*MultiHeadAttentionBuilder) WithNumKVHeads

func (b *MultiHeadAttentionBuilder) WithNumKVHeads(numKVHeads int) *MultiHeadAttentionBuilder

WithNumKVHeads sets the number of key/value heads for Grouped Query Attention (GQA).

When numKVHeads < numHeads, each group of numHeads/numKVHeads query heads shares the same key/value head. This reduces the KV projection and KV cache size while retaining most of the quality of full multi-head attention.

Special cases:

  • numKVHeads == numHeads: standard multi-head attention (MHA), the default.
  • numKVHeads == 1: multi-query attention (MQA), all query heads share one KV head.

numHeads must be divisible by numKVHeads. This method is incompatible with UseQKVProjection when query == key == value and numKVHeads != numHeads, since the fused QKV path assumes equal head counts for Q and KV.

func (*MultiHeadAttentionBuilder) WithOutputDim

func (b *MultiHeadAttentionBuilder) WithOutputDim(outputDim int) *MultiHeadAttentionBuilder

WithOutputDim defines the output dimension of the final projection, from the flattened attention heads.

It defaults to the value of the last dimension of `values` passed as input (`inputValueDim`).

func (*MultiHeadAttentionBuilder) WithPosition

func (b *MultiHeadAttentionBuilder) WithPosition(position *Node) *MultiHeadAttentionBuilder

WithPosition sets the position of the input sequence in the generated sequence. This is used by positional encoders (like RoPE) to compute the correct positional indices.

func (*MultiHeadAttentionBuilder) WithPositionalEncoder

func (b *MultiHeadAttentionBuilder) WithPositionalEncoder(encoder pos.Encoder) *MultiHeadAttentionBuilder

WithPositionalEncoder sets a positional encoder to use.

Note: Only pos.QKEncoder is actually called. A pos.PreEncoder is ignored, since they should be applied before the first MultiHeadAttention layer.

func (*MultiHeadAttentionBuilder) WithPreProjected

func (b *MultiHeadAttentionBuilder) WithPreProjected(preProjected bool) *MultiHeadAttentionBuilder

WithPreProjected configures the builder to assume the query, key, and value inputs are already projected, so they don't need to be projected again internally.

func (*MultiHeadAttentionBuilder) WithQKRMSNorm

func (b *MultiHeadAttentionBuilder) WithQKRMSNorm(epsilon float64) *MultiHeadAttentionBuilder

WithQKRMSNorm applies RMSNorm to the query and key projections before attention (used by models like Gemma 2 and Gemma 3).

func (*MultiHeadAttentionBuilder) WithQueryKeyMatrixMask

func (b *MultiHeadAttentionBuilder) WithQueryKeyMatrixMask(queryKeyMatrixMask *Node) *MultiHeadAttentionBuilder

WithQueryKeyMatrixMask sets a mask matrix that defines which queries can attend to which keys. Defaults to no mask, meaning all queries are accessible.

Shape should be `[batch_size, numHeads, <query_elements>, <key_elements>]`, or `[batch_size, <query_elements>, <key_elements>]` if the mask is the same for every head.

Either use WithKeyMask and WithQueryMask separately or use WithKeyQueryMatrixMask, but not both.

Optionally, one can also WithCausalMask, which is combined (logical-and) to any given mask.

func (*MultiHeadAttentionBuilder) WithQueryKeyScale

func (b *MultiHeadAttentionBuilder) WithQueryKeyScale(scale float64) *MultiHeadAttentionBuilder

WithQueryKeyScale overrides the default scaling factor (1 / sqrt(keyQueryDim)) for the attention scores.

func (*MultiHeadAttentionBuilder) WithQueryMask

func (b *MultiHeadAttentionBuilder) WithQueryMask(queryMask *Node) *MultiHeadAttentionBuilder

WithQueryMask sets a mask for queries that are actually valid and should be used. Defaults to no mask, meaning all queries are used. See also WithKeyMask.

Shape should be `[batch_size, numHeads, <query_elements>]`, or `[batch_size, <query_elements>]` if the mask is the same for every head.

Either use WithKeyMask and WithQueryMask separately or use WithKeyQueryMatrixMask, but not both. Optionally, one can also WithCausalMask, which is combined (logical-and) to any given mask.

func (*MultiHeadAttentionBuilder) WithRoPE deprecated

WithRoPE enables Rotary Position Embeddings on query and key projections. baseFreq is typically 10000.0 (default from RoFormer paper). RoPE is applied after projections and works with both training and generation modes.

Deprecated: Use WithPositionalEncoder, passing a pos.RoPE instead.

func (*MultiHeadAttentionBuilder) WithScoreSoftCap

WithScoreSoftCap sets the soft cap for the attention score computation. When set to > 0, the attention scores are capped using tanh: cap * tanh(scores / cap) (see nn.SoftCap).

func (*MultiHeadAttentionBuilder) WithSeqLens

func (b *MultiHeadAttentionBuilder) WithSeqLens(querySeqLen, keyValueSeqLen *Node) *MultiHeadAttentionBuilder

WithSeqLens supplies per-batch actual sequence lengths (int32 [B] nodes) for padding masking. Both querySeqLen and keyValueSeqLen must be set together, or both nil; passing exactly one non-nil argument panics. Mutually exclusive with an explicit query/key matrix mask.

func (*MultiHeadAttentionBuilder) WithSlidingWindow

func (b *MultiHeadAttentionBuilder) WithSlidingWindow(window int) *MultiHeadAttentionBuilder

WithSlidingWindow sets the sliding window size for local attention. When > 0, it restricts the maximum distance between query and key tokens that can be attended to. This is used for sliding window attention architectures (like Gemma 3 sliding layers).

func (*MultiHeadAttentionBuilder) WithValueHeadDim

func (b *MultiHeadAttentionBuilder) WithValueHeadDim(valueDim int) *MultiHeadAttentionBuilder

WithValueHeadDim allows finer configuration on the dimension of the projection used for the value for each head. It defaults to the value given by `headDim`.

Directories

Path Synopsis
Package kvcache implements a flexible key-value (KV) cache for transformer models.
Package kvcache implements a flexible key-value (KV) cache for transformer models.
Package pos provides positional encoding implementations for attention mechanisms.
Package pos provides positional encoding implementations for attention mechanisms.

Jump to

Keyboard shortcuts

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