Documentation
¶
Overview ¶
Package nn provides low-level implementations of common neural network operations.
It handles routing to backend-specific fused ops when available, and otherwise falls back to standard graph computations. It does not manage variables directly: functions take and return *github.com/gomlx/gomlx/core/graph.Node values instead of accepting a github.com/gomlx/gomlx/ml/model.Scope or github.com/gomlx/gomlx/ml/model.Store.
Typically, users building models will not call these functions directly. Instead, they should use higher-level layer packages (such as github.com/gomlx/gomlx/ml/layers or github.com/gomlx/gomlx/ml/layers/fnn), which automatically manage model variables and call the underlying implementations here.
Index ¶
- Constants
- func Dense(x, weight, bias *Node, weightLayout compute.DenseLayout, ...) *Node
- func FusedScaledDotProductAttention(query, key, value *Node, axesLayout compute.AttentionAxesLayout, ...) *Node
- func LayerNorm(x *Node, axes []int, epsilon float64, gamma, beta, mask *Node) *Node
- func LinearAttention(query, key, value *Node, axesLayout compute.AttentionAxesLayout, ...) (output, finalState *Node)
- func QuantizedDense(x, weight, bias *Node, cfg QuantizedDenseConfig, ...) *Node
- func QuantizedGather(table, indices *Node, quant *Quantization) *Node
- func RMSNorm(x, gamma *Node, axes []int, epsilon, gammaOffset float64, ...) *Node
- func RoPE(x, cos, sin *Node, config RoPEConfig) *Node
- func SoftCap(input *Node, cap float64) *Node
- type FusedSDPAConfig
- type LinearAttentionConfig
- type RoPEConfig
Constants ¶
const ( // DefaultLinearAttentionChunkSize is the default chunk size used by the decomposed // fallback for scalar-decay and non-decay linear attention recurrences // (Simple Linear Attention, Mamba-2/SSD, DeltaNet, Gated DeltaNet). DefaultLinearAttentionChunkSize = 64 // DefaultLinearAttentionChannelDecayChunkSize is the default chunk size used by the // decomposed fallback for channel-wise decay recurrences (GLA, KDA), keeping the // exact overflow-free [C, C, Dk] intra-chunk factor compact. DefaultLinearAttentionChannelDecayChunkSize = 16 )
Variables ¶
This section is empty.
Functions ¶
func Dense ¶
func Dense(x, weight, bias *Node, weightLayout compute.DenseLayout, optionalActivation ...activation.Type) *Node
Dense performs a dense (linear) transformation with optional activation:
y = activation(x @ weight + bias) (if weightLayout is DenseLayoutInputOutputs) y = activation(x @ weight^T + bias) (if weightLayout is DenseLayoutOutputsInput)
weight has shape [in_features, out_features...] for DenseLayoutInputOutputs, or [out_features..., in_features] for DenseLayoutOutputsInput. bias is optional (nil means no bias).
optionalActivation is optional; if omitted or activations.TypeNone, no activation is applied.
If the backend supports fused Dense, the optimized native implementation is used; otherwise the operation is decomposed into primitives. Fallback is handled automatically via graphbridge.FusedOpCaller.
func FusedScaledDotProductAttention ¶ added in v0.28.38
func FusedScaledDotProductAttention( query, key, value *Node, axesLayout compute.AttentionAxesLayout, configs ...*FusedSDPAConfig, ) *Node
FusedScaledDotProductAttention computes scaled dot-product attention using the backend's fused op when available, falling back automatically to decomposed graph operations otherwise.
It does not depend on model.Store. For higher-level attention with dropout, score soft-capping, or returning attention coefficients, use package ml/layers/attention.
func LayerNorm ¶
LayerNorm performs layer normalization on x over the given axes with the specified epsilon. gamma and beta are optional (nil means skip scale/shift). mask is optional (nil means no masking). When a mask is provided, the decomposed path is always used (fused ops don't support masking).
If the backend supports fused LayerNorm, the optimized native implementation is used; otherwise the operation is decomposed into primitives. Fallback is handled automatically via graphbridge.FusedOpCaller.
func LinearAttention ¶ added in v0.28.44
func LinearAttention( query, key, value *Node, axesLayout compute.AttentionAxesLayout, configs ...*LinearAttentionConfig, ) (output, finalState *Node)
LinearAttention computes causal linear attention or the (gated) delta rule over pre-projected query, key, and value tensors.
If the backend supports OpTypeFusedLinearAttention, the fused kernel is invoked via graphbridge.FusedOpCallerMulti; otherwise it seamlessly falls back to a decomposed chunkwise parallel scan (using exact block-recursive WY/UT triangular inversion for delta rules). It does not depend on model.Store; for a full stateful layer with projections, short convolution, and output gating, use package ml/layers/attention/linear.
Inputs:
- query: [B, S, numKHeads, Dk] (BSHD) or [B, numKHeads, S, Dk] (BHSD)
- key: same shape as query
- value: [B, S, numVHeads, Dv] (BSHD) or [B, numVHeads, S, Dv] (BHSD), where numVHeads must be a positive multiple of numKHeads.
Returns:
- output: same layout and dtype as query/value, with shape [B, S, numVHeads, Dv] (BSHD) or [B, numVHeads, S, Dv] (BHSD).
- finalState: [B, numVHeads, Dk, Dv] (Float64 if inputs are Float64, Float32 otherwise) when config.ReturnFinalState is true, or nil when config.ReturnFinalState is false.
func QuantizedDense ¶
func QuantizedDense( x, weight, bias *Node, cfg QuantizedDenseConfig, optionalActivation ...activation.Type, ) *Node
QuantizedDense performs a quantized dense (linear) projection with optional bias, activation, pre-quantized input activations, and optional output re-quantization:
- Weight-only quantization (cfg.XQuantization == nil): y = activation(x @ dequant(weight, cfg.WeightQuantization) + bias) (transposing dequant(weight) when cfg.WeightLayout == compute.DenseLayoutOutputsInput).
- Pre-quantized x + weight integer matmul (cfg.XQuantization != nil): supports QuantLinear (exact Int32 accumulation + xScale * wScale) and QuantGGML (GGMLQ8_0 / GGMLQ8_K paired block dot products).
- Bias conventions (when bias != nil, shape [N]):
- Floating-point bias: added in floating-point AFTER dequantization / (xScale * wScale) rescaling and BEFORE activation / OutputQuantization.
- Int32 bias (only for QuantLinear XQuantization when neither xScale nor wScale is sub-blocked along K): added directly to the Int32 accumulator BEFORE converting to Float32 and multiplying by xScale * wScale, i.e. z[m, n] = float32(acc_int32[m, n] + bias[n]) * (xScale[m] * wScale[n]).
- Optional output quantization (cfg.OutputQuantization != nil): re-quantizes the post-activation float output to Int8 or Uint8.
An optional activation.Type may be passed as optionalActivation (convenience shorthand when cfg.Activation is left at its zero value ActivationNone).
Migration note: bias is the 3rd parameter (matching nn.Dense), QuantGGML weights require cfg.WeightLayout = compute.DenseLayoutOutputsInput, scalar [] and 1D [N] scales no longer need [K, NumBlocks] broadcasts, and QuantLinear ZeroPoint uses the standard pre-scale convention real = (float(q) - float(zp)) * scale (legacy additive offsets convert via ZeroPoint = Neg(Div(oldOffset, scale))).
When the backend supports fused FusedQuantizedDense (and FusedQuantizedDenseVJP for weight-only fine-tuning such as QLoRA), the native implementation is used without materializing dequantized [K, N] float weights in forward or backward passes; otherwise QuantizedDense falls back automatically to primitive graph operations.
func QuantizedGather ¶
func QuantizedGather(table, indices *Node, quant *Quantization) *Node
QuantizedGather performs a quantized row gather (embedding lookup): gathers rows from a quantized or packed sub-byte table and unpacks/dequantizes only the selected rows on-the-fly.
This is the quantized analogue of graph.Gather for row lookups (similar to llama.cpp's ggml_get_rows) and is also the supported way to gather rows from packed sub-byte tables (Int2, Uint2, Int4, Uint4), which graph.Gather does not support directly.
Supported modes:
- quant == nil or QuantNone: gathers rows from Int2/Uint2/Int4/Uint4 (or Int8/Uint8) tables and unpacks them losslessly to Int8 (for signed Int2/Int4/Int8) or Uint8 (for unsigned Uint2/Uint4/Uint8). If PackedDType is set, table may be stored bit-packed in Uint8 with shape [vocabSize, K / ValuesPerStorageUnit] and logical dtype PackedDType. Supports both static and dynamic batch dimensions on any backend.
- QuantGGML: table is [vocabSize, bytesPerRow] Uint8 with native GGML block layout; output is Float32. Static batch dimensions fall back to ggml.GatherDecomposed; dynamic batch dimensions require a backend with OpTypeQuantizedGather (e.g. "go").
- QuantLinear: table is [vocabSize, K] Int2/Uint2/Int4/Uint4/Int8/Uint8 (or [vocabSize, K/vpb] Uint8 when PackedDType is set) with Scale (Float32/Float16/BFloat16) and optional ZeroPoint; output matches Scale's DType. Note that PackedDType does not apply to ZeroPoint. Supports both static and dynamic batch dimensions on any backend.
- QuantNF4: table is [vocabSize, K] Int4/Uint4/Int8/Uint8 (or [vocabSize, K/2] Uint8 when PackedDType is set) with Scale (Float32/Float16/BFloat16); output matches Scale's DType.
Parameters:
- table: quantized or sub-byte table (rank 2).
- indices: integer tensor with last dimension = 1 (same as Gather convention). For embeddings: [batch, seqLen, 1].
- quant: quantization metadata, or nil to gather and unpack sub-byte/8-bit rows to Int8/Uint8.
Output: tensor with shape [batch..., K].
func RMSNorm ¶ added in v0.28.43
func RMSNorm(x, gamma *Node, axes []int, epsilon, gammaOffset float64, normDType dtypes.DType) *Node
RMSNorm performs Root Mean Square (RMS) normalization on x over the given axes:
y = x / sqrt(mean(x^2) + epsilon) * (gamma + gammaOffset)
gamma is optional (nil skips scaling). normDType specifies the dtype used for internal reduction/normalization statistics (InvalidDType defaults to Float32 for 16-bit floats and x's dtype otherwise).
If the backend supports FusedLayerNorm with RMSNorm=true, the fused kernel is used; otherwise it falls back cleanly to decomposed primitives.
func RoPE ¶ added in v0.28.43
func RoPE(x, cos, sin *Node, config RoPEConfig) *Node
RoPE applies Rotary Position Embeddings to x using pre-computed cos and sin tables.
If the backend supports OpTypeFusedRoPE, the fused kernel is used (with a single-kernel inverse-rotation VJP for dx); otherwise the operation seamlessly falls back to primitive graph ops via graphbridge.FusedOpCaller.
Inputs:
- x: floating-point tensor shaped [..., seqLen, ..., headDim], where config.SeqAxis identifies the sequence axis (negative values count from the end).
- cos, sin: pre-computed cosine and sine tables shaped [seqLen, rotaryHalfDim], [b_0, ..., b_{seqAxis-1}, seqLen, rotaryHalfDim], or full-rank [d_0, ..., d_{rank-2}, rotaryHalfDim]. For Float16/BFloat16 x, cos/sin may be either x's dtype or Float32 (preferred for higher accuracy).
func SoftCap ¶
func SoftCap(input *Node, cap float64) *Node
SoftCap performs a smooth (soft) capping/limiting of the input values within the range [-cap, cap] using the hyperbolic tangent function:
output = cap * tanh(input / cap)
This function is commonly used in Gemma models (Gemma-2, Gemma-3, and Gemma-4) to soft-cap attention scores, preventing them from growing too large and stabilizing softmax/gradients.
Types ¶
type FusedSDPAConfig ¶ added in v0.28.38
type FusedSDPAConfig struct {
// Scale is the scaling factor for attention scores (typically 1/sqrt(head_dim)).
// If 0, it defaults to 1/sqrt(head_dim), where head_dim is the last dimension of query.
Scale float64
// Causal applies a causal (lower-triangular) attention mask.
// Mutually exclusive with Mask.
Causal bool
// Mask is an optional boolean or additive float mask broadcastable to the score shape
// ([batch, numHeads, q_seq, kv_seq] for LayoutBHSD, or [batch, q_seq, numHeads, kv_seq] for LayoutBSHD).
// Mutually exclusive with Causal and QuerySeqLen/KVSeqLen.
Mask *Node
// Bias is an optional additive attention-score bias [batch, numHeads, q_seq, kv_seq]
// added to scores before softmax.
Bias *Node
// QuerySeqLen and KVSeqLen are optional per-batch actual sequence lengths (int32 [B]).
// Only supported with compute.AttentionAxesLayoutBSHD; mutually exclusive with Mask.
QuerySeqLen *Node
KVSeqLen *Node
// QuantizedMatmuls indicates quantized matmul semantics when supported by the backend.
QuantizedMatmuls bool
}
FusedSDPAConfig holds optional configuration for FusedScaledDotProductAttention. Zero values provide sensible defaults (Scale = 1/sqrt(headDim), no mask, non-causal).
type LinearAttentionConfig ¶ added in v0.28.44
type LinearAttentionConfig struct {
// LogDecay (g) is the optional log-space decay factor (values should be <= 0; state is scaled by exp(g)).
// Supported shapes depend on axesLayout:
// - nil: no decay (Simple Linear Attention or un-gated DeltaNet).
// - rank 3: scalar decay per head ([B, S, H] for BSHD, [B, H, S] for BHSD; Mamba-2/SSD or Gated DeltaNet).
// - rank 4: channel-wise decay per key dim ([B, S, H, Dk] for BSHD, [B, H, S, Dk] for BHSD; GLA or KDA).
LogDecay *Node
// Beta is the optional delta-rule update gate (typically in (0, 1)), shaped [B, S, H] for BSHD
// or [B, H, S] for BHSD.
// - nil: disables the delta erasure rule (Simple Linear Attention, Mamba-2/SSD, GLA).
// - non-nil: enables the surgical delta rule S_t = decay(S_{t-1})(I - beta_t k_t k_t^T) + beta_t k_t v_t^T
// (DeltaNet, Gated DeltaNet, KDA).
Beta *Node
// InitialState is the optional initial recurrent state shaped [B, H, Dk, Dv].
// If nil, starts from a zero state.
InitialState *Node
// UseQKL2Norm applies L2 normalization along head_k_dim (with eps=1e-6) to query and key.
UseQKL2Norm bool
// QueryScale scales queries by this factor. If 0, defaults to 1 / sqrt(Dk).
// Set to a negative value (e.g. -1) to disable query scaling (scale = 1.0).
QueryScale float64
// TiledKVHeads controls how Q and K heads map to V heads when numVHeads > numKHeads:
// - false (default, HuggingFace / FLA): interleaved [k0, k0, ..., k1, k1, ...].
// - true (llama.cpp / GGUF): tiled [k0, k1, ..., k0, k1, ...].
TiledKVHeads bool
// ReturnFinalState, when true, returns the final recurrent state [B, numVHeads, Dk, Dv] as the
// second return value. When false, finalState is returned as nil, allowing fused backends to
// omit materializing/writing the final state.
ReturnFinalState bool
// QuantizedMatmuls is an optional optimization hint passed to FusedLinearAttention
// allowing backends to use dynamic quantized matmuls where beneficial.
QuantizedMatmuls bool
// ChunkSize sets the chunk length along the sequence axis for the decomposed chunkwise fallback.
// Must be a power of 2 >= 2 (e.g., 16, 32, 64).
// If <= 0, defaults to DefaultLinearAttentionChunkSize (64) for scalar/no decay and
// DefaultLinearAttentionChannelDecayChunkSize (16) for channel-wise decay.
ChunkSize int
// UnrollChunks, when true (and sequence length is static), unrolls the inter-chunk scan in
// the decomposed fallback instead of emitting a graph.While loop. This enables reverse-mode
// autodiff (core/autodiff.Gradient) through LinearAttention during training.
// Ignored when sequence length is dynamic (which always uses graph.While).
UnrollChunks bool
// SkipDecomposedVJP, when true, skips constructing the decomposed alternate graph for VJP
// when the backend supports OpTypeFusedLinearAttention (useful during inference to avoid
// dead subgraph construction overhead).
SkipDecomposedVJP bool
}
LinearAttentionConfig configures LinearAttention. Zero values provide sensible defaults (Simple Linear Attention without decay or delta rule, QueryScale = 1/sqrt(Dk), interleaved GVA heads, ReturnFinalState = false).
type RoPEConfig ¶ added in v0.28.43
type RoPEConfig = compute.FusedRoPEConfig
RoPEConfig configures Rotary Position Embeddings (RoPE) for nn.RoPE.