nn

package
v0.28.36 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 10 Imported by: 4 modules, 1 package

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

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 InternalFusedOpCaller.

func LayerNorm

func LayerNorm(x *Node, axes []int, epsilon float64, gamma, beta, mask *Node) *Node

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 InternalFusedOpCaller.

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 embedding lookup: gathers rows from a quantized embedding table and dequantizes only the selected rows on-the-fly.

This is the quantized analogue of graph.Gather for embedding lookups, similar to llama.cpp's ggml_get_rows. The full embedding table stays in native quantized format and only the rows selected by indices are dequantized to float32.

All supported GGML types (Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, IQ4_NL, Q2_K, Q3_K, Q4_K, Q5_K, Q6_K, Q8_K) have a decomposed graph-level fallback and work on any backend (including XLA) when batch dimensions are static. Dynamic batch dimensions require a backend with a fused executor (e.g. "go"); other backends will panic.

Parameters:

  • table: [vocabSize, bytesPerRow] Uint8 with native GGML block layout.
  • indices: integer tensor with last dimension = 1 (same as Gather convention). For embeddings: [batch, seqLen, 1].
  • quant: quantization metadata. Only QuantGGML scheme is supported.

Output: float32 tensor with shape [batch..., K] where K is the logical embedding dimension derived from the block format: K = (bytesPerRow / bytesPerBlock) * valuesPerBlock.

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

This section is empty.

Jump to

Keyboard shortcuts

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