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 ¶
- 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 QuantizedDense(x, weight, bias *Node, cfg QuantizedDenseConfig, ...) *Node
- func QuantizedGather(table, indices *Node, quant *Quantization) *Node
- func SoftCap(input *Node, cap float64) *Node
- type FusedSDPAConfig
Constants ¶
This section is empty.
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 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 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).