layers

package
v0.28.18 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: Apache-2.0 Imports: 16 Imported by: 5 modules, 19 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 layers holds a collection of common modeling layers. It includes dense layer, convolutions (TODO), activation functions, dropout (TODO), etc.

A small convention on naming: typically layers are nouns (like "Convolution", "Dense" (layer), "MultiHeadAttention"), while computations are usually verbs ("Convolve", "Reduce..", "Multiply (Mul)", etc.).

Index

Constants

View Source
const (
	HookPriorityEarly   = -100
	HookPriorityDefault = 0
	HookPriorityLate    = 100
)

Standard hook priorities. Lower values execute first.

View Source
const (
	// ParamL2Regularization scope hyperparameter defines the L2 regularization of kernels.
	// Each layer may decide independently to implement it or not.
	//
	// This is an alias to regularizers.ParamL2
	// Dense, DenseWithBias, FNN, kan and Convolution kernels look at this hyperparameter.
	// The value should be a float64.
	// The default is `0.0`.
	//
	// Deprecated: use regularizers.ParamL2
	ParamL2Regularization = "l2_regularization"

	// ParamDropoutRate scope hyperparameter defines the amount of dropout applied when DropoutFromScope is used.
	// Should be a value from `0.0` to `1.0`, where 0 means no dropout, and 1 would drop everything out.
	//
	// It is only applied if `Scope.IsTraining() == true`, that is, during evaluation/inference it is
	// ignored.
	//
	// The default is `0.0`, which means no dropout.
	ParamDropoutRate = "dropout_rate"

	// ParamDropPathProbability provides the probability of DropPathFromScope to drop paths.
	//
	// This is only applied if the model actually calls DropPathFromScope.
	//
	// Default is `0.0`, which means never do any DropPath.
	ParamDropPathProbability = "droppath_prob"
)
View Source
const (
	// NormalizationLayerNorm is the value for norm.LayerNorm.
	NormalizationLayerNorm = "layer"
	// NormalizationRMSNorm is the value for norm.RMSNorm.
	NormalizationRMSNorm = "rms"
	// NormalizationBatchNorm is the value for norm.BatchNorm.
	NormalizationBatchNorm = "batch"
	// NormalizationDyT is the value for norm.DynamicTanh.
	// DyT is a drop-in replacement for layer normalization; see norm.DynamicTanh for details.
	NormalizationDyT = "dyt"
	// NormalizationNone is the value for no normalization.
	NormalizationNone = "none"
)

Variables

View Source
var (
	// ParamDropBlockProbability is the hyperparameter that sets the default DropBlock dropout probability. Default is float64(0.0).
	ParamDropBlockProbability = "dropblock_prob"

	// ParamDropBlockSize is the hyperparameter that set the default DropBlock block size. Default is int(3).
	ParamDropBlockSize = "dropblock_size"
)
View Source
var (
	// KnownNormalizers is a map of normalizer string to a function that applies them
	// with the default values, with the feature axis set to -1. This will only work
	// for the most standard problems, since anything with a different shape will need
	// special feature axes configuration for each normalization technique.
	//
	// It includes "none", which is a no-op.
	//
	// Notice that some normalizers use variables, and they need to be unique
	// in their scope (`Scope.In(scope)`) -- except if one wants to deliberately share
	// normalization variables across more than one application.
	KnownNormalizers = map[string]func(scope *model.Scope, input *Node) *Node{
		NormalizationBatchNorm: func(scope *model.Scope, input *Node) *Node {
			return norm.BatchNorm(scope, input, -1).Done()
		},
		NormalizationLayerNorm: func(scope *model.Scope, input *Node) *Node {
			return norm.LayerNorm(scope, input, -1).Done()
		},
		NormalizationRMSNorm: func(scope *model.Scope, input *Node) *Node {
			return norm.RMSNorm(scope, input).Done()
		},
		NormalizationDyT: func(scope *model.Scope, input *Node) *Node {
			return norm.DynamicTanh(scope, input).Done()
		},
		NormalizationNone: func(scope *model.Scope, input *Node) *Node {
			return input
		},
	}

	// ParamNormalization scope hyperparameter defines the type of normalization to use
	// between layers of a neural network.
	//
	// It is used if the model calls NormalizeFromScope or MaskedNormalizeFromScope on the embeddings in
	// between layers.
	// This is usually applied after a residual sum (but model choices varies).
	//
	// Valid values are "layer" for LayerNormalization, "batch" for BatchNorm,
	// "rms" for RMSNorm, "dyt" for DynamicTanh, or "none".
	//
	// Notice that this won't work for special shapes setups.
	// New will normalize on the batch axis (assumed to be axis-0), and
	// LayerNormalization and RMSNorm will normalize across the layer values, assumed to be the last.
	//
	// The default is `layer`.
	ParamNormalization = "normalization"
)

Functions

func AddL2Regularization deprecated

func AddL2Regularization(scope *model.Scope, amount *Node, values ...*Node)

AddL2Regularization calculates the L2 of the given values (typically variable nodes returned by model.Variable.NodeValue()), scale by the given amount (typically a constant) and then train.AddLoss the resulting value, having the effect of regularizing the weights (variables).

Deprecated: use package regularizers instead.

func AddL2RegularizationStatic deprecated added in v0.9.0

func AddL2RegularizationStatic(scope *model.Scope, amount float64, values ...*Node)

AddL2RegularizationStatic is like AddL2Regularization, but takes the `amount` as a static Go float64 value.

Deprecated: use package regularizers instead.

func ApplyPostLinearHooks added in v0.28.17

func ApplyPostLinearHooks(scope *model.Scope, input, output *Node) *Node

ApplyPostLinearHooks executes all registered post-linear hooks in priority order.

func AssertQuantilesForPWLCalibrationValid added in v0.5.0

func AssertQuantilesForPWLCalibrationValid[T cmp.Ordered](values []T)

AssertQuantilesForPWLCalibrationValid validates that raw values for quantiles are ok to be used for PieceWiseLinearCalibration. It checks for:

  • Enough data points.
  • Monotonicity of data points: quantiles should always be increasing.

Errors are reported back with `panic`.

func ClearPostLinearHooks added in v0.28.17

func ClearPostLinearHooks()

ClearPostLinearHooks removes all registered post-linear hooks. This is primarily intended for testing.

func Dense

func Dense(scope *model.Scope, input *Node, useBias bool, outputDimensions ...int) *Node

Dense adds a single dense linear layer, a learnable linear transformation. Optionally, it can include a bias term. Weight layout is compute.DenseLayoutInputOutputs.

It creates a "dense" sub-scope under `scope`.

It automatically adds regularization to the weights (not to biases) configured in hyperparameters -- see regularizers.FromScope.

If the input has shape `[<batch dimensions...>, featureDimension]`, the output will have shape `[<batch dimensions...>, <outputDimensions...>]`.

See also DenseWithLayout to specify a weight layout, and FNN for a more configurable (including hidden layers) version.

func DenseWithBias

func DenseWithBias(scope *model.Scope, input *Node, outputDimensions ...int) *Node

DenseWithBias adds a single dense linear layer, a learnable linear transformation plus a bias term.

It creates a "dense" sub-scope under `scope`.

It the input has shape `[<batch dimensions...>, featureDimension]`, the output will have shape `[<batch dimensions...>, <outputDimensions...>]`.

See also FNN for a more configurable (including hidden layers) version.

func DenseWithLayout added in v0.28.1

func DenseWithLayout(scope *model.Scope, input *Node, layout compute.DenseLayout, useBias bool, outputDimensions ...int) *Node

DenseWithLayout adds a single dense linear layer with a specific weight layout.

It creates a "dense" sub-scope under `scope`.

If layout is compute.DenseLayoutInputOutputs, weights have shape `[inputLastDimension, outputDimensions...]`. If layout is compute.DenseLayoutOutputsInput, weights have shape `[outputDimensions..., inputLastDimension]`.

Optionally, it can include a bias term. It automatically adds regularization to the weights (not to biases) configured in hyperparameters -- see regularizers.FromScope.

If the input has shape `[<batch dimensions...>, featureDimension]`, the output will have shape `[<batch dimensions...>, <outputDimensions...>]`.

func DropPath added in v0.17.0

func DropPath(scope *model.Scope, x, dropProbability *Node) *Node

DropPath drops with a certain probability whole examples (paths). It assumes x is shaped [batchSize, ...], and each batchSize example is independently either fully "dropped" (set to zero) or not.

This is commonly applied on residual models, with updates like `x = Add(residual, x)`, which can be replaced with `x = Add(residual, DropPath(x, dropProbability))`. Another usage example is dropping whole positional embedding.

If it is not training or dropProbability is nil, it is a no-op.

See also DropPathFromScope.

func DropPathFromScope added in v0.28.0

func DropPathFromScope(scope *model.Scope, x *Node) *Node

DropPathFromScope will execute DropPath if the hyperparameter ParamDropPathProb is set to a value > 0. If ParamDropPathProb is not set or if not training, this is a no-op.

func Dropout

func Dropout(scope *model.Scope, input *Node, dropoutRate *Node) *Node

Dropout randomly replace the input with zeros if scope.IsTraining() is true. Otherwise, it's a no op (it returns input). If the input is float, it scales the output by 1/(1-dropoutRate) to preserve the mean of the values of the input.

func DropoutFromScope added in v0.28.0

func DropoutFromScope(scope *model.Scope, x *Node) *Node

DropoutFromScope applies a dropout configured in the scope parameters keyed by ParamDropoutRate.

If it is 0.0 this is a no-op. If `Scope.IsTraining() == false` this is also a no-op, so it doesn't impact evaluation or inference.

func DropoutNormalize

func DropoutNormalize(scope *model.Scope, input *Node, dropoutRate *Node, normalize bool) *Node

DropoutNormalize randomly replace the input with zeros if scope.IsTraining() is true. Otherwise, it's a no op (it returns input). If normalize is set, it scales the output by 1/(1-dropoutRate) to preserve the mean of the input values.

func DropoutStatic added in v0.9.0

func DropoutStatic(scope *model.Scope, input *Node, dropoutRate float64) *Node

DropoutStatic is the same as Dropout, but it takes the `dropoutRate` as a static value, given as a float64. If `dropoutRate <= 0` or it's not training, this is a no-op.

func Embedding

func Embedding(scope *model.Scope, input *Node, dtype dtypes.DType, vocabSize, dimension int, indicesAreSorted ...bool) *Node

Embedding creates an embedding table with vocabSize elements (typically a vocabulary size) each of dimension values -- so a [vocabSize, dimension] variable table.

It then converts each integer value of the input to an embedding of the given dimension size. The input must have an integer dtype, and the last dimension must be of size 1. If it's not of size one, an extra dimension is added to the end. All values of the input must smaller than vocabSize, otherwise it will fail -- no checking is explicitly made.

indicesAreSorted should be set to true only if the input is guaranteed to be sorted (ascending). This allows some optimizations in some compute. The default is false (for compatibility), in future versions this argument will be made obligatory.

The output has rank one larger than the input, with the last dimension the same as the embedding dimension.

func IsDropoutActive added in v0.28.0

func IsDropoutActive(scope *model.Scope, g *Graph) bool

IsDropoutActive returns true if dropout is active (i.e. if it's training). If using DropoutStatic, also check that dropoutRate > 0.

func MaskedNormalizeFromScope added in v0.28.0

func MaskedNormalizeFromScope(scope *model.Scope, input, mask *Node) *Node

MaskedNormalizeFromScope applies a normalization (or none) according to the hyperparameter ParamNormalization configured in the model. The `mask` is actually optional and can be set to nil if not using a mask.

This is not recommended for images, since one may want to normalize over specific axes.

func MustNormalizeByName

func MustNormalizeByName(scope *model.Scope, normalization string, input *Node) *Node

MustNormalizeByName applies the requested normalization using default parameters. If an invalid normalization is given, it panics with an error.

This will only work for the most standard problems, since anything with a different shape will need special feature axes configuration for each normalization technique.

It's a simple wrapper around KnownNormalizers, if one wants to handle errors, just check for its values. For valid values see KnownNormalizers.

Some layer libraries will use this by default for you, taking the value from the scope -- e.g: fnn.New.

But if not, one example use:

``` var flagNormalization = flag.String("norm", "none",

fmt.Sprintf("Type of layer normalization to use. Valid values: %q.",
	types.SortedKeys(layers.KnownNormalizers)))

...

func ModelGraph(...) {
    ...
    logits = MustNormalizeByName(scope, *flagNormalization, logits)
    ...
}

```

func Normalize added in v0.4.0

func Normalize(x *Node, independentAxes ...int) *Node

Normalize shifts and scales the input such that the mean becomes zero and the variance one. It calculates `(x - mean(x)) / (sigma(x))`, where sigma is the standard deviation.

The parameter `independentAxes` list axes that should not be normalized together. A typical value is -1, the feature axis (last axis), so that each feature gets its own normalization.

func NormalizeFromScope added in v0.28.0

func NormalizeFromScope(scope *model.Scope, input *Node) *Node

NormalizeFromScope applies a normalization (or none) according to the hyperparameter ParamNormalization configured in the model.

This is not recommended for images, since one may want to normalize over specific axes.

func PieceWiseLinearCalibration

func PieceWiseLinearCalibration(scope *model.Scope, input, keypoints *Node, outputTrainable bool) *Node

PieceWiseLinearCalibration creates a piece-wise linear function from the input, splitting it in the given keypoints with outputs initialized with values from 0 to 1.

The keypoints are typically quantiles of the input feature, starting with the minimum value and ending on the maximum. It must have rank-1 and be of the same DType as input. Its values must be ordered, and cannot be repeated (this may lead to NaNs). Consider using AssertQuantilesForPWLCalibrationValid on the quantiles.

If outputTrainable is set to true, the outputs mapped to the keypoints are made trainable, and may change to values outside the range [0, 1].

In any case, if the input is beyond the first or last keypoint, the output of the function will flatten, preventing any extrapolations (often they are bad in NN).

This is a simpler version to the one described here: https://www.tensorflow.org/lattice/api_docs/python/tfl/layers/PWLCalibration

func PieceWiseLinearCalibrationCascaded

func PieceWiseLinearCalibrationCascaded(scope *model.Scope, input, keypoints *Node, outputTrainable bool) *Node

PieceWiseLinearCalibrationCascaded is a similar implementation for PieceWiseLinearCalibration that is equally powerful (express the same functions) simpler (fewer ops) and faster, but is parametrizing differently (cascaded linear functions), and may have different learning characteristics when doing gradient descent.

func RegisterPostLinearHook added in v0.28.17

func RegisterPostLinearHook(priority int, hook PostLinearHook)

RegisterPostLinearHook registers a hook called after every linear projection, ordered by priority (lower priority values are called first).

It is thread-safe and can be called from init() functions or at runtime.

Types

type ConvBuilder

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

ConvBuilder is a helper to build a convolution computation. Create it with Convolution, set the desired parameters, and when all is set, call Done.

func Convolution

func Convolution(scope *model.Scope, x *Node) *ConvBuilder

Convolution prepares one convolution on x with the given kernel for an arbitrary number of spatial dimensions (1D, 2D, 3D, etc.).

It returns a ConvBuilder object for configuration. Once it is set up, call `ConvBuilder.Done` and it will return the convolved x.

It includes support for padding, strides, dilations, grouping, and an added bias. Browse through ConvBuilder to see the capabilities, and their defaults.

Two parameters need setting: Channels (or channels) and KernelSize. It will fail if they are not set.

The shape of x should be `[batch, <spatial_dimensions...>, input_channels]` if configured with `ConvBuilder.ChannelsAxis(images.ChannelsLast)`, the default.

If one sets `ConvBuilder.ChannelsAxis(images.ChannelsFirst)`, the shape should be `[batch, input_channels, <spatial_dimensions...>]` instead.

The output rank and order of the output axes are the same as the input's. Their dimensions depend on the configuration options.

func (*ConvBuilder) BatchGroupCount added in v0.22.0

func (conv *ConvBuilder) BatchGroupCount(groupCount int) *ConvBuilder

BatchGroupCount splits batches into independent processing groups. Used for cross-batch interactions like ShuffleNet's channel shuffle.

When BatchGroupCount != 1, the kernel's shape changes: the batch dimension of the input is divided by the group count, creating separate convolution groups where each group processes a subset of the batch.

The output shape will have the same spatial dimensions as a regular convolution but with the batch dimension affected by the grouping.

Note: Back-propagation is not yet implemented for this feature.

Reference: https://www.tensorflow.org/api_docs/python/tf/data/Dataset#batch

func (*ConvBuilder) ChannelGroupCount added in v0.22.0

func (conv *ConvBuilder) ChannelGroupCount(groupCount int) *ConvBuilder

ChannelGroupCount splits input/output channels into independent groups. Equivalent to TensorFlow's "groups" parameter in tf.nn.convNd operations.

When groupCount != 1, the kernel's shape changes: the input channels dimension of the kernel must equal (input_channels / group_count). This effectively creates separate convolution groups where each group processes a subset of input channels and produces a subset of output channels.

For depthwise convolution, set groups = input_channels (see tf.nn.depthwise_conv2d). The output shape will have the same spatial dimensions as a regular convolution but with channel dimensions affected by the grouping.

Side effects:

  • Kernel shape: The kernel's input channel dimension becomes (input_channels / group_count)
  • Output shape: The output maintains the same spatial dimensions as regular convolution, but each group independently maps its input channels to output channels
  • Performance: Can reduce computation cost by limiting connections between channels
  • Memory usage: Reduces the number of parameters in the kernel

Note: Back-propagation is not yet implemented for this feature.

Reference: https://www.tensorflow.org/api_docs/python/tf/data/Dataset#group_by_window

func (*ConvBuilder) Channels added in v0.22.0

func (conv *ConvBuilder) Channels(filters int) *ConvBuilder

Channels sets the number of output channels. There is no default, and this number must be set before Done is called.

func (*ConvBuilder) ChannelsAxis added in v0.3.0

func (conv *ConvBuilder) ChannelsAxis(channelsAxisConfig images.ChannelsAxisConfig) *ConvBuilder

ChannelsAxis configures the axis for the channels (aka. "depth" or "features") dimension. The default is `images.ChannelsLast`, meaning the "channels" dimension comes last.

Note: `images` refers to package `github.com/gomlx/gomlx/core/tensors/images`.

It returns the modified Config object, so calls can be cascaded.

func (*ConvBuilder) CurrentScope added in v0.3.0

func (conv *ConvBuilder) CurrentScope() *ConvBuilder

CurrentScope configures the convolution not to create a sub-scope for the kernel weights it needs, and instead use the current one provided in Convolution.

By default, Convolution will create a sub-scope named "conv".

func (*ConvBuilder) DilationPerAxis added in v0.22.0

func (conv *ConvBuilder) DilationPerAxis(dilations ...int) *ConvBuilder

DilationPerAxis sets the kernel dilations for each spatial axis of the convolution. The default is 1 for every axis.

Specifies the kernel up-sampling rate. In the literature, the same parameter is sometimes called input stride or dilation. The effective kernel size used for the convolution will be `kernel_shape + (kernel_shape - 1) * (dilation - 1)`, obtained by inserting (dilation-1) zeros between consecutive elements of the original filter in the spatial dimension.

One cannot use strides and dilation at the same time.

func (*ConvBuilder) DilationPerDim deprecated

func (conv *ConvBuilder) DilationPerDim(dilations ...int) *ConvBuilder

DilationPerDim is a deprecated alias for DilationPerAxis.

Deprecated: Use DilationPerAxis instead.

func (*ConvBuilder) Dilations

func (conv *ConvBuilder) Dilations(dilation int) *ConvBuilder

Dilations sets the dilations of the convolution. It sets the same value for every dimension.

The default is 1. A value > 1 is also called "atrous convolution".

It specifies the kernel up-sampling rate. In the literature, the same parameter is sometimes called input stride or kernel dilation. The effective kernel size used for the convolution will be `kernel_shape + (kernel_shape - 1) * (dilation - 1)`, obtained by inserting (dilation-1) zeros between consecutive elements of the original filter in the spatial dimension.

One cannot use strides and dilation at the same time.

func (*ConvBuilder) Done

func (conv *ConvBuilder) Done() *Node

Done indicates that the Convolution layer is finished being configured. It then creates the convolution and it's kernels (variables) and returns the resulting Node.

func (*ConvBuilder) Filters deprecated

func (conv *ConvBuilder) Filters(channels int) *ConvBuilder

Filters is a deprecated alias for Channels.

Deprecated: Use Channels instead.

func (*ConvBuilder) KernelSize

func (conv *ConvBuilder) KernelSize(size int) *ConvBuilder

KernelSize sets the kernel size for every axis. There is no default, and this value must be set before Done is called.

You can also use KernelSizePerAxis to set the kernel size per axis individually.

func (*ConvBuilder) KernelSizePerAxis added in v0.22.0

func (conv *ConvBuilder) KernelSizePerAxis(dimensions ...int) *ConvBuilder

KernelSizePerAxis sets the kernel size for each axis (axis). There is no default, and this value must be set before Done is called.

You can also use KernelSize to set the kernel size the same for all dimensions.

func (*ConvBuilder) KernelSizePerDim deprecated

func (conv *ConvBuilder) KernelSizePerDim(dimensions ...int) *ConvBuilder

KernelSizePerDim is a deprecated alias for KernelSizePerAxis.

Deprecated: Use KernelSizePerAxis instead.

func (*ConvBuilder) NoPadding

func (conv *ConvBuilder) NoPadding() *ConvBuilder

NoPadding removes any paddings, so if the kernel spatial dimensions > 1, the output shape will be reduced on the edges.

This is the default.

func (*ConvBuilder) PadSame

func (conv *ConvBuilder) PadSame() *ConvBuilder

PadSame adds paddings on the edges of x such that in the end the output of the convolution has the same shape as the input (assuming strides=1).

The default is NoPadding.

func (*ConvBuilder) Regularizer added in v0.11.0

func (conv *ConvBuilder) Regularizer(regularizer regularizer.Regularizer) *ConvBuilder

Regularizer to be applied to the learned weights (but not the biases). Default is none.

To use more than one type of Regularizer, use regularizers.Combine, and set the returned combined regularizer here.

The default is regularizers.FromScope, which is configured by regularizers.ParamL1 and regularizers.ParamL2.

func (*ConvBuilder) StridePerAxis added in v0.22.0

func (conv *ConvBuilder) StridePerAxis(strides ...int) *ConvBuilder

StridePerAxis sets the strides for each spatial dimension of the convolution. The default is 1 for every dimension.

The stride is how many steps to move after a convolution. A value of 2 will half the input size, since a convolution will be done at every other position, and so on. It can be defined separately per dimension.

One cannot use strides and dilation at the same time.

func (*ConvBuilder) StridePerDim deprecated

func (conv *ConvBuilder) StridePerDim(strides ...int) *ConvBuilder

StridePerDim is a deprecated alias for StridePerAxis.

Deprecated: Use StridePerAxis instead.

func (*ConvBuilder) Strides

func (conv *ConvBuilder) Strides(strides int) *ConvBuilder

Strides sets the strides of the convolution. It sets the same value for every dimension. The default is 1.

The stride is how many steps to move after a convolution. A value of 2 will half the input size, since a convolution will be done at every other position, and so on. It can be defined separately per dimension.

One cannot use strides and dilation at the same time.

func (*ConvBuilder) UseBias

func (conv *ConvBuilder) UseBias(useBias bool) *ConvBuilder

UseBias sets whether to add a trainable bias term to the convolution. Default is true.

type DropBlockConfig added in v0.17.0

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

DropBlockConfig is created with a DropBlock.

func DropBlock added in v0.17.0

func DropBlock(scope *model.Scope, x *Node) *DropBlockConfig

DropBlock implements a block dropout, as described in [1].

Parameters:

  • scope: the Scope, and it's used to check if it is training, and the default dropout probability and block size as a hyperparameter. DropBlock is a no-op during inference (not training) or if no dropout probability was configured.
  • x: operand to be regularized with block dropout. The default is to assume x is shaped [batchSize, <...spatial axes...>, channelsAxis]. Use ChannelsAxis or FullShape to configure that.

The dropout probability and the block sizes are read by default from the scope hyperparameters (see ParamDropBlockProbability and ParamDropBlockSize). But they can be optionally configured as well.

It returns a configuration object that can be further configured. Call Done when finished configuring, and it will return the regularized value.

[1] "DropBlock: A regularization method for convolutional networks", Golnaz Ghiasi, Tsung{-}Yi Lin and Quoc V. Le, https://arxiv.org/abs/1810.12890v1

func (*DropBlockConfig) ChannelsAxis added in v0.17.0

func (cfg *DropBlockConfig) ChannelsAxis(channelsAxisConfig images.ChannelsAxisConfig) *DropBlockConfig

ChannelsAxis configures the axis for the channels (aka. "depth" or "features") dimension. The default is `images.ChannelsLast`, meaning the "channels" dimension comes last.

Note: `images` refers to package `github.com/gomlx/gomlx/core/tensors/images`.

If you don't want to exclude the batch size and channels from the pooling, use FullShape instead.

It returns the modified Config object, so calls can be cascaded.

func (*DropBlockConfig) Done added in v0.17.0

func (cfg *DropBlockConfig) Done() *Node

Done applies the configured DropBlock to the operand x, and returns the regularized value.

func (*DropBlockConfig) FullShape added in v0.17.0

func (cfg *DropBlockConfig) FullShape() *DropBlockConfig

FullShape configures the DropBlock operation to consider all its axes as part of the block, with no special considerations for the batch or channel axes.

See ChannelsAxis to handle batch and channels specially, and BlockSizes to set the block size for each specific axis.

The default is configured with ChannelsAxis(images.ChannelsLast).

func (*DropBlockConfig) WithBlockSize added in v0.17.0

func (cfg *DropBlockConfig) WithBlockSize(blockSize int) *DropBlockConfig

WithBlockSize sets the block size to be used for all spatial axes.

The default is 3.

func (*DropBlockConfig) WithBlockSizes added in v0.17.0

func (cfg *DropBlockConfig) WithBlockSizes(blockSizes ...int) *DropBlockConfig

WithBlockSizes configures a different block size per spatial dimension. The same number of values must be set here as the number of SpatialAxes.

Default is 3 for every spatial axis. See also WithBlockSize.

func (*DropBlockConfig) WithDropoutProbability added in v0.17.0

func (cfg *DropBlockConfig) WithDropoutProbability(prob float64) *DropBlockConfig

WithDropoutProbability configures the dropout probability to use. It is the expectation of ratio of "pixels" (or voxels if 3d) that will be dropped out in blocks from the image (if 2D).

By default, it reads ParamDropBlockProbability hyperparameter from scope.

func (*DropBlockConfig) WithDropoutProbabilityNode added in v0.17.0

func (cfg *DropBlockConfig) WithDropoutProbabilityNode(prob *Node) *DropBlockConfig

WithDropoutProbabilityNode configures the dropout probability to use with a dynamic (graph.Node) probability. prob must be a Float32 scalar node. It is the expectation of ratio of "pixels" (or voxels if 3d) that will be dropped out in blocks from the image (if 2D).

By default, it reads ParamDropBlockProbability hyperparameter from scope and use that as a constant.

type PostLinearHook added in v0.28.17

type PostLinearHook func(scope *model.Scope, input, output *Node) *Node

PostLinearHook is called after a linear transformation (e.g. dense layer in FNN, attention, etc.). It receives the layer's scope, the input to the linear projection (before transformation), and the output of the linear projection (after base weights and bias, but before activation/dropout/norm). It returns the updated output node.

Directories

Path Synopsis
Package activations implements several common activations, and includes a generic Apply method to apply an activation by its type.
Package activations implements several common activations, and includes a generic Apply method to apply an activation by its type.
Package attention implements multi-head attention and related utilities.
Package attention implements multi-head attention and related utilities.
kvcache
Package kvcache implements a flexible key-value (KV) cache for transformer models.
Package kvcache implements a flexible key-value (KV) cache for transformer models.
pos
Package pos provides positional encoding implementations for attention mechanisms.
Package pos provides positional encoding implementations for attention mechanisms.
Package bsplines provide a GoMLX version of github.com/gomlx/bsplines: it provides evaluation of bsplines curves, that can be used as layers.
Package bsplines provide a GoMLX version of github.com/gomlx/bsplines: it provides evaluation of bsplines curves, that can be used as layers.
Package fnn implements a generic FNN (Feedforward Neural Network) with various configurations.
Package fnn implements a generic FNN (Feedforward Neural Network) with various configurations.
Package kan implements a generic Kolmogorov–Arnold Networks, as described in https://arxiv.org/pdf/2404.19756
Package kan implements a generic Kolmogorov–Arnold Networks, as described in https://arxiv.org/pdf/2404.19756
Package lstm provides a minimal "Long Short-Term Memory RNN" (LSTM) [1] implementation.
Package lstm provides a minimal "Long Short-Term Memory RNN" (LSTM) [1] implementation.
Package norm implements normalization layers for GoMLX, including Batch, Layer, and RMS normalization.
Package norm implements normalization layers for GoMLX, including Batch, Layer, and RMS normalization.
Package peft implements parameter-efficient fine-tuning layers for GoMLX.
Package peft implements parameter-efficient fine-tuning layers for GoMLX.
Package rational implements "learnable rational functions".
Package rational implements "learnable rational functions".
Package regularizers adds tools to facilitate add regularization to the weights learned.
Package regularizers adds tools to facilitate add regularization to the weights learned.
Package vnn implements the Vector Neuron Networks operators described in https://arxiv.org/abs/2104.12229
Package vnn implements the Vector Neuron Networks operators described in https://arxiv.org/abs/2104.12229

Jump to

Keyboard shortcuts

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