norm

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: 15 Imported by: 4 modules, 9 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 norm implements normalization layers for GoMLX, including Batch, Layer, and RMS normalization.

Index

Constants

View Source
const (
	// AveragesUpdatesTriggerParam is a boolean parameter set in case batch normalization was used.
	// See UpdateBatchNormAverages.
	AveragesUpdatesTriggerParam = "batch_normalization_averages_updates_trigger"
)
View Source
const (
	// BatchNormalizationScopeName is used as sub-scope for all batch normalization variables.
	BatchNormalizationScopeName = "batch_normalization"
)

Variables

View Source
var (
	// ParamLayerNormEpsilon is the scope parameter that defines the default layer normalization epsilon value.
	// The default is 1e-3.
	ParamLayerNormEpsilon = "layer_norm_epsilon"

	// ParamLayerNormCenter is the scope parameter that defines whether to center the norm by default.
	// The default is true.
	ParamLayerNormCenter = "layer_norm_center"

	// ParamLayerNormLearnedGain is the scope parameter that defines whether to learn a gain for the
	// layer norm, that multiplies its output.
	// The default is true.
	ParamLayerNormLearnedGain = "layer_norm_learned_gain"

	// ParamLayerNormLearnedScale is an alias to ParamLayerNormLearnedGain.
	// Deprecated: renamed to follow original papers nomenclature.
	ParamLayerNormLearnedScale = ParamLayerNormLearnedGain

	// ParamLayerNormRescale is the scope parameter that defines whether to rescale the layer
	// by dividing it by the square root of the variance.
	// The default is true.
	ParamLayerNormRescale = "layer_norm_rescale"

	// ParamLayerNormL2Regularization is the scope parameter that defines the amount of L2 regularization
	// to apply to the learned gain, if one is defined.
	// The default is 0.0.
	ParamLayerNormL2Regularization = "layer_norm_l2_regularization"

	// ParamLayerNormNormalizationDType is the dtype to use when doing the normalization.
	//
	// Low precision dtypes (Float16, BFloat16) usually lead to NaN when doing ReduceSum/ReduceMean,
	// which layer normalization does.
	//
	// If this value is different than the dtype of the input, the normalization will convert the values
	// to this dtype first.
	//
	// The default value (and empty string) means to use Float32 if the input dtype is 16 bits only, otherwise
	// use the same dtype as the input.
	ParamLayerNormNormalizationDType = "layer_norm_dtype"
)
View Source
var (
	// ParamDynamicTanhAlpha is the scope hyperparameter that defines the initial value for the
	// learnable alpha parameter. The default is 0.5.
	//
	// Alpha is a scalar shared across the input and scales values before the tanh nonlinearity.
	ParamDynamicTanhAlpha = "dynamic_tanh_alpha"
)

Functions

func ResetBatchNormWeights

func ResetBatchNormWeights(backend compute.Backend, store *model.Store) error

ResetBatchNormWeights resets the weights of the moving averages, forcing them to be reinitialized to 0. It searches for all variables under scope named "batch_normalization"

This is not a graph building function, it sets the materialized values to zero.

It is a no-op if no batch-normalization was used.

Usually this method is not used directly, instead use UpdateBatchNormAverages.

func UpdateBatchNormAverages

func UpdateBatchNormAverages(trainer *train.Trainer, oneEpochDS train.Dataset) (bool, error)

UpdateBatchNormAverages resets the weights of the moving averages and recalculates them over the given oneEpochDS dataset and the trainer. It uses the scope assigned to the trainer.

It is a no-op if no batch-normalization was used.

The oneEpochDS dataset (typically, the same as a training data evaluation dataset) should be a 1-epoch training data dataset, and it can use evaluation batch sizes. If oneEpochDS is nil, it disables the updating of the averages.

It returns whether batch normalization was used and averages were updated.

An error is only returned if it attempts to update the averages.

See discussions: - https://www.mindee.com/blog/batch-normalization - https://discuss.pytorch.org/t/batch-norm-instability/32159/14

Types

type BatchNormBuilder

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

BatchNormBuilder is a builder for configuring a batch normalization layer. Create it with BatchNorm, set the desired parameters, and when all is set, call Done.

func BatchNorm

func BatchNorm(scope *model.Scope, x *Node, featureAxis int) *BatchNormBuilder

BatchNorm creates a builder for a batch normalization layer on the input. It includes a scaling and offset factor, and normalization over the batch entries. It maintains a moving average mean and variance of the inputs which is later used during inference.

featureAxis is the axis over which **not to normalize**: this will normalize over the other dimensions, calculating the mean and variance by reducing all other dimensions. E.g: if your input is `[batch_size, features]` you should use featureAxis=1 (same as -1) to normalize over the batch; if your input is an image of shape `[batch_size, height, width, channels]` you should use featureAxis=3 (same as -1) to normalize over the batch and all the pixels, so each channel is normalized differently, but normalization happens over all the pixels of the whole batch.

Notice the difference between LayerNorm, that normalizes over the feature dimensions, as opposed to the batch dimension.

To ease setting its parameters, it returns a BatchNormBuilder object for configuration. Once it is set up call `BatchNormBuilder.Done` and it will return the normalized x. Browse through BatchNormBuilder to see the capabilities and the defaults.

Batch normalization behaves differently during training and inference: during training it normalizes over the batch (so it likely won't work well for very small batch sizes), and in inference, it normalizes using the collected moving average of the mean and variance.

Based on paper "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift" (Sergey Ioffe, Christian Szegedy), https://arxiv.org/abs/1502.03167.

See also UpdateBatchNormAverages to update the running averages after the training of the model -- or just before evaluations. Because during training the target averages of the mean and variances are moving (as the model changes), they are often biased and suboptimal, UpdateBatchNormAverages fixes that and often provides some significant gains.

FutureWork: 1. Support padding by not normalizing parts that weren't touched. 2. Support selection of multiple features axes.

func (*BatchNormBuilder) Center

func (builder *BatchNormBuilder) Center(value bool) *BatchNormBuilder

Center defines whether the batch normalization tries to center the input by adding a learned offset. Default to true.

This is also called the β (beta) parameter, and referred to as a "learnable offset".

func (*BatchNormBuilder) CurrentScope

func (builder *BatchNormBuilder) CurrentScope() *BatchNormBuilder

CurrentScope configures BatchNorm not to create a new sub-scope named BatchNormalizationScopeName for its variables. This allows more control on scope names, but it breaks things that rely on batch normalization variables to be under BatchNormalizationScopeName (e.g.: ResetBatchNormWeights).

func (*BatchNormBuilder) Done

func (builder *BatchNormBuilder) Done() *Node

Done finishes configuring the BatchNorm and generates the graph computation to normalize the input.

func (*BatchNormBuilder) Epsilon

func (builder *BatchNormBuilder) Epsilon(value float64) *BatchNormBuilder

Epsilon is a small float added to variance to avoid dividing by zero. It defaults to 1e-3.

Notice Keras default is 1e-3 (the one we use), but PyTorch's default of 1e-05.

func (*BatchNormBuilder) FrozenAverages

func (builder *BatchNormBuilder) FrozenAverages(frozen bool) *BatchNormBuilder

FrozenAverages defines whether the moving averages for mean and variance should be kept frozen for this layer.

This is useful in transfer learning when the sub-model being incorporated was trained on a different distribution, and we don't want to impact that.

func (*BatchNormBuilder) Momentum

func (builder *BatchNormBuilder) Momentum(value float64) *BatchNormBuilder

Momentum sets the momentum of the moving averages collected for the mean and variance of the values. BatchNorm maintains moving averages for the mean and variance during training. This averaged mean and variance is used during inference for normalization. The default is 0.99.

Notice Keras default is 0.99 (the one we use), but PyTorch's default of 0.9.

This has no effect if one sets `Trainable(false)`.

func (*BatchNormBuilder) Scale

func (builder *BatchNormBuilder) Scale(value bool) *BatchNormBuilder

Scale defines whether the batch normalization tries to scale the input by adding a learned scale. Default to true.

This is also called the γ (gamma) parameter.

func (*BatchNormBuilder) Trainable

func (builder *BatchNormBuilder) Trainable(trainable bool) *BatchNormBuilder

Trainable defines whether the batch normalization is trainable. If set to `false` it is frozen, and none of its parameters are changeable. The default is `true`.

Independent of the value set here, if the scope is not set for training ( see `model.Store.IsTraining()`) like during evaluation and inference, the BatchNormBuilder will generate code for inference only.

func (*BatchNormBuilder) UseBackendInference

func (builder *BatchNormBuilder) UseBackendInference(value bool) *BatchNormBuilder

UseBackendInference uses a backend version of batch normalization inference. The alternative is a manually defined batch normalization inference, which is differentiable. Only used if training is false.

The default is true.

type DynamicTanhBuilder

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

DynamicTanhBuilder holds the configuration for Dynamic Tanh (DyT). Once finished configuring, call DynamicTanhBuilder.Done().

func DynamicTanh

func DynamicTanh(scope *model.Scope, operand *Node) *DynamicTanhBuilder

DynamicTanh starts the configuration of a Dynamic Tanh (DyT) operation, as described in "Transformers without Normalization" (https://arxiv.org/abs/2503.10622).

DyT is a drop-in replacement for layer normalization in transformer blocks. Unlike LayerNorm or RMSNorm, it does not compute mean or variance. Instead it applies:

DyT(x) = tanh(alpha * x) * gamma + beta

Where:

  • alpha is a learnable scalar (initialized to 0.5 by default)
  • gamma is a learnable per-feature scale (initialized to 1)
  • beta is a learnable per-feature offset (initialized to 0)

Parameters are stored under the "dynamic_tanh" sub-scope as "alpha", "gamma", and "beta". Gamma and beta are shaped to the last dimension of the input (the feature dimension) and broadcast to the full input rank.

For a transformer activation of shape [batch, seq, features], gamma and beta have shape [features] and are broadcast across batch and sequence positions.

func (*DynamicTanhBuilder) Done

func (dyt *DynamicTanhBuilder) Done() *Node

Done uses the current configuration to apply Dynamic Tanh. It returns a node with the same shape as the input operand.

func (*DynamicTanhBuilder) WithAlpha

func (dyt *DynamicTanhBuilder) WithAlpha(alpha float64) *DynamicTanhBuilder

WithAlpha sets the initial value for the learnable alpha parameter and returns the updated builder. The default is read from ParamDynamicTanhAlpha (0.5 if not set).

type LayerNormBuilder

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

LayerNormBuilder is a helper to build a layer normalization computation. Create it with LayerNorm, set the desired parameters and when all is set, call Done. See LayerNorm for details.

func LayerNorm

func LayerNorm(scope *model.Scope, x *Node, normalizingAxes ...int) *LayerNormBuilder

LayerNorm performs a layer normalization on the input. It includes a scaling and offset factor, and normalization over the feature entries.

This is an alternative to BatchNorm, that doesn't suffer from the problem of variance on small batch sizes, nor does it need to keep a moving average of the normalization parameters. Commonly used with transformer layers (see MultiHeadAttention).

normalizingAxes are the axes over which to normalize: mean and variance are calculated over these axes and the values are then normalized. E.g: if your input is `[batch_size, features]` you should use `normalizingAxes=[1]` (same as -1) to normalize over the `features` axis; if your input is an image of shape [batch_size, height, width, channels] one common approach is to normalize over the image, so `normalizingAxes=[1 2]`, but not over the channels.

Notice the difference between BatchNorm, that normalizes over the batch dimension, as opposed to the feature dimensions.

The layer norm may have a learned gain and offset, controlled by LayerNormBuilder.LearnedGain and LayerNormBuilder.LearnedOffset settings, enabled by default.

To ease setting its parameters it returns a LayerNormBuilder object for configuration. Once it is set up call `LayerNormBuilder.Done` and it will return the normalized x. Browse through LayerNormBuilder to check for its capabilities, and the defaults.

Layer normalization behaves the same during training and inference -- as opposed to batch normalization.

Based on paper "Layer Normalization" (Jimmy Lei Ba, Jamie Ryan Kiros, Geoffrey E. Hinton), https://arxiv.org/abs/1607.06450

FutureWork: support padding by not normalizing parts that weren't touched ...

func (*LayerNormBuilder) Done

func (builder *LayerNormBuilder) Done() *Node

Done finishes configuring the LayerNorm and generates the graph computation to normalize the input.

func (*LayerNormBuilder) Epsilon

func (builder *LayerNormBuilder) Epsilon(value float64) *LayerNormBuilder

Epsilon is a small float added to variance to avoid dividing by zero. It defaults to the value given by ParamLayerNormEpsilon.

It is not used if ScaleNormalization is set to false.

func (*LayerNormBuilder) LearnedGain

func (builder *LayerNormBuilder) LearnedGain(value bool) *LayerNormBuilder

LearnedGain defines whether the layer normalization tries to apply a multiplying gain the input, a tensor with the shape of the combined normalizing axes -- so it changes the direction of the inputs, it's not simply a gain.

Default is true.

func (*LayerNormBuilder) LearnedOffset

func (builder *LayerNormBuilder) LearnedOffset(value bool) *LayerNormBuilder

LearnedOffset defines whether the layer normalization tries to center the input by adding a learned offset. It defaults to true.

The offset will be learned separately for each axis that is not the batch (assumed to be axis 0 only) and not any of the normalizingAxes.

func (*LayerNormBuilder) Mask

func (builder *LayerNormBuilder) Mask(mask *Node) *LayerNormBuilder

Mask sets the mask for the input values. False values in the mask should be ignored for the normalization.

func (*LayerNormBuilder) ScaleNormalization

func (builder *LayerNormBuilder) ScaleNormalization(value bool) *LayerNormBuilder

ScaleNormalization defines whether the input's scale is normalized by the square root of the variance. The default is true, and this is the original paper specification, but in some cases it works best without it.

type RMSNormBuilder

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

RMSNormBuilder holds the configuration for RMSNorm. Once finished configuring, call RMSNormBuilder.Done()

func RMSNorm

func RMSNorm(scope *model.Scope, operand *Node) *RMSNormBuilder

RMSNorm starts the configuration of an RMS normalization operation, as described in https://arxiv.org/abs/1910.07467.

It normalizes the input with a simple:

	RMS(a) = Sqrt(1/n * \sum{a_i^2})
 RMSNorm(a) = a_i / RMS(a) * g_i

Where g_i is a learnable gain (scale), enabled by default.

Call RMSNormBuilder.Done when you finished the configuration.

func (*RMSNormBuilder) Done

func (rms *RMSNormBuilder) Done() *Node

Done uses the current configuration to perform RMSNorm. It returns the normalized operand.

func (*RMSNormBuilder) WithEpsilon

func (rms *RMSNormBuilder) WithEpsilon(epsilon float64) *RMSNormBuilder

WithEpsilon sets the epsilon value used in RMSNorm configuration and returns the updated builder. The default value is 1e-6.

func (*RMSNormBuilder) WithNormalizationAxes

func (rms *RMSNormBuilder) WithNormalizationAxes(axes ...int) *RMSNormBuilder

WithNormalizationAxes sets the axes over which to normalize in the RMSNorm configuration and returns the updated builder. The default value is -1 (the last axis).

func (*RMSNormBuilder) WithScale

func (rms *RMSNormBuilder) WithScale(useScale bool) *RMSNormBuilder

WithScale sets whether to use the gain parameter in the RMSNorm configuration and returns the updated builder.

func (*RMSNormBuilder) WithScaleOffset

func (rms *RMSNormBuilder) WithScaleOffset(offset float64) *RMSNormBuilder

WithScaleOffset sets a fixed value to be added to the learned scale. Some models like Gemma and Gemma-2 add 1.0 to the scale.

Jump to

Keyboard shortcuts

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