Main Content

positionEmbeddingLayer

Position embedding layer

Since R2023b

    Description

    A position embedding layer maps sequential or spatial indices to vectors. Use this layer in transformer neural networks to encode information about data positions in a sequence or image.

    Creation

    Description

    layer = positionEmbeddingLayer(outputSize,maxPosition) creates a position embedding layer and sets the OutputSize and MaxPosition properties.

    example

    layer = positionEmbeddingLayer(outputSize,maxPosition,Name=Value) creates a position embedding layer and sets the PositionDimension, Name, Parameters and Initialization, and Learning Rate and Regularization properties using one or more name-value arguments.

    example

    Properties

    expand all

    Position Embedding

    This property is read-only.

    Number of channels in the layer output, specified as a positive integer.

    Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    This property is read-only.

    Maximum sequence length or spatial index in the layer input, specified as a positive integer.

    Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    This property is read-only.

    Dimension of positions to embed, specified as one of these values:

    • "auto" — For sequence or spatial-temporal input, embed the temporal positions, which is equivalent to using "temporal". For 1-D image input, embed the spatial positions, which is equivalent to using "spatial".

    • "temporal" — Embed the temporal positions.

    • "spatial" — Embed the spatial positions.

    Parameters and Initialization

    Function to initialize the weights, specified as one of these values:

    • "narrow-normal" — Initialize the weights by independently sampling from a normal distribution with zero mean and a standard deviation of 0.01.

    • "glorot" — Initialize the weights with the Glorot initializer [2] (also known as Xavier initializer). The Glorot initializer independently samples from a uniform distribution with zero mean and variance 2/(numIn + numOut), where numIn = MaxPosition and numOut = OutputSize.

    • "he" — Initialize the weights with the He initializer [3]. The He initializer samples from a normal distribution with zero mean and a variance of 2/numIn, where numIn = MaxPosition.

    • "zeros" — Initialize the weights with zeros.

    • "ones" — Initialize the weights with ones.

    • Function handle – Initialize the weights with a custom function. If you specify a function handle, then the function must be of the form weights = func(sz), where sz is the size of the weights.

    The layer initializes the weights only when the Weights property is empty.

    Data Types: char | string | function_handle

    Learnable weights, specified as an OutputSize-by-MaxPosition numeric array or [].

    The layer weights are learnable parameters. You can specify the initial value of the weights directly using the Weights property of the layer. When you train a network, if the Weights property of the layer is nonempty, then the trainnet function uses the Weights property as the initial value. If the Weights property is empty, then the software uses the initializer specified by the WeightsInitializer property of the layer.

    Data Types: single | double

    Learning Rate and Regularization

    Learning rate factor for the weights, specified as a nonnegative scalar.

    The software multiplies this factor by the global learning rate to determine the learning rate for the weights in this layer. For example, if WeightLearnRateFactor is 2, then the learning rate for the weights in this layer is twice the current global learning rate. The software determines the global learning rate based on the settings you specify using the trainingOptions function.

    Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    L2 regularization factor for the weights, specified as a nonnegative scalar.

    The software multiplies this factor by the global L2 regularization factor to determine the L2 regularization for the weights in this layer. For example, if WeightL2Factor is 2, then the L2 regularization for the weights in this layer is twice the global L2 regularization factor. You can specify the global L2 regularization factor using the trainingOptions function.

    Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    Layer

    Layer name, specified as a character vector or string scalar. For Layer array input, the trainnet and dlnetwork functions automatically assign names to layers with the name "".

    The PositionEmbeddingLayer object stores this property as a character vector.

    Data Types: char | string

    This property is read-only.

    Number of inputs to the layer, returned as 1. This layer accepts a single input only.

    Data Types: double

    This property is read-only.

    Input names, returned as {'in'}. This layer accepts a single input only.

    Data Types: cell

    This property is read-only.

    Number of outputs from the layer, returned as 1. This layer has a single output only.

    Data Types: double

    This property is read-only.

    Output names, returned as {'out'}. This layer has a single output only.

    Data Types: cell

    Examples

    collapse all

    Create a position embedding layer with an output size of 300 and a maximum position of 128.

    layer = positionEmbeddingLayer(300,128)
    layer = 
      PositionEmbeddingLayer with properties:
    
                         Name: ''
                   OutputSize: 300
                  MaxPosition: 128
            PositionDimension: 'auto'
           WeightsInitializer: 'narrow-normal'
        WeightLearnRateFactor: 1
               WeightL2Factor: 1
    
       Learnable Parameters
                      Weights: []
    
       State Parameters
        No properties.
    
    Use properties method to see a list of all properties.
    
    

    Create a dlnetwork object.

    net = dlnetwork;

    Create a neural network containing a position embedding layer.

    numChannels = 1;
    
    embeddingOutputSize = 64;
    numWords = 128;
    maxPosition = 128;
    
    numHeads = 4;
    numKeyChannels = 4*embeddingOutputSize;
    
    layers = [ 
        sequenceInputLayer(numChannels,Name="input")
        wordEmbeddingLayer(embeddingOutputSize,numWords,Name="word-emb")
        positionEmbeddingLayer(embeddingOutputSize,maxPosition,Name="pos-emb");
        additionLayer(2,Name="add")
        selfAttentionLayer(numHeads,numKeyChannels,AttentionMask="causal")
        fullyConnectedLayer(numWords)
        softmaxLayer];
    
    net = addLayers(net,layers);
    net = connectLayers(net,"word-emb","add/in2");

    View the neural network architecture.

    plot(net)
    axis off
    box off

    Figure contains an axes object. The hidden axes object contains an object of type graphplot.

    Algorithms

    expand all

    References

    [1] Gehring, Jonas, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. "Convolutional Sequence to Sequence Learning." In Proceedings of the 34th International Conference on Machine Learning - Volume 70, 1243–52. ICML’17. Sydney, NSW, Australia: JMLR.org, 2017

    [2] Glorot, Xavier, and Yoshua Bengio. "Understanding the Difficulty of Training Deep Feedforward Neural Networks." In Proceedings of the Thirteenth International Conference on Artificial Intelligence and Statistics, 249–356. Sardinia, Italy: AISTATS, 2010. https://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf

    [3] He, Kaiming, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. "Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification." In 2015 IEEE International Conference on Computer Vision (ICCV), 1026–34. Santiago, Chile: IEEE, 2015. https://doi.org/10.1109/ICCV.2015.123

    Extended Capabilities

    Version History

    Introduced in R2023b