PositionEmbeddingLayer - Position embedding layer - MATLAB (original) (raw)
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
Syntax
Description
`layer` = positionEmbeddingLayer(`outputSize`,`maxPosition`)
creates a position embedding layer and sets the OutputSize andMaxPosition properties.
Properties
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 variance2/(numIn + numOut)
, wherenumIn = MaxPosition
andnumOut = OutputSize
."he"
— Initialize the weights with the He initializer[3]. The He initializer samples from a normal distribution with zero mean and a variance of2/numIn
, wherenumIn = 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)
, wheresz
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
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
Layer
Data Types: char
| string
This property is read-only.
Number of inputs to the layer, stored as 1
. This layer accepts a single input only.
Data Types: double
This property is read-only.
Input names, stored as {'in'}
. This layer accepts a single input only.
Data Types: cell
This property is read-only.
Number of outputs from the layer, stored as 1
. This layer has a single output only.
Data Types: double
This property is read-only.
Output names, stored as {'out'}
. This layer has a single output only.
Data Types: cell
Examples
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.
Show all properties
Create a dlnetwork
object.
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
Algorithms
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.
The output of the layer has the same number of dimensions as the input. In the output, each vector in position p
over the channel dimension isWeights(:,p)
, where Weights
is the learnable embedding weights.
For example:
- For vector-sequence data
X
represented by anumChannels
-by-numObservations
-by-numTimeSteps
array, wherenumChannels
,numObservations
, andnumTimeSteps
are the numbers of channels, observations, and time steps of the input, respectively, the output is aOutputSize
-by-numObservations
-by-numTimeSteps
arrayY
, where each vector inY(:,:,t)
over the channel dimension isWeights(:,t)
. - For 1-D image data
X
represented by aheight
-by-numChannels
-by-numObservations
array, whereheight
,numChannels
, andnumObservations
are the height, number of channels, and number of observations of the input images, respectively, the output is aheight
-by-OutputSize
-by-numObservations
arrayY
, where each vector inY(i,:,:)
over the channel dimension isWeights(:,i)
. - For 2-D image sequence data
X
represented by aheight
-by-width
-by-numChannels
-by-numObservations
-numTimeSteps
array, whereheight
andwidth
are the height and width of the input image sequences, respectively, andnumChannels
,numObservations
, andnumTimeSteps
are the numbers of channels, observations, and time steps of the input image sequences, respectively, the output is aheight
-by-width
-by-OutputSize
-by-numObservations
-by-numTimeSteps
arrayY
, where each vector inY(:,:,:,:,t)
over the channel dimension isWeights(:,t)
.
Layers in a layer array or layer graph pass data to subsequent layers as formatted dlarray objects. The format of a dlarray
object is a string of characters in which each character describes the corresponding dimension of the data. The format consists of one or more of these characters:
"S"
— Spatial"C"
— Channel"B"
— Batch"T"
— Time"U"
— Unspecified
For example, you can describe 2-D image data that is represented as a 4-D array, where the first two dimensions correspond to the spatial dimensions of the images, the third dimension corresponds to the channels of the images, and the fourth dimension corresponds to the batch dimension, as having the format "SSCB"
(spatial, spatial, channel, batch).
You can interact with these dlarray
objects in automatic differentiation workflows, such as those for developing a custom layer, using a functionLayer object, or using the forward and predict functions withdlnetwork
objects.
This table shows the supported input formats of PositionEmbeddingLayer
objects and the corresponding output format. If the software passes the output of the layer to a custom layer that does not inherit from the nnet.layer.Formattable
class, or aFunctionLayer
object with the Formattable
property set to 0
(false
), then the layer receives an unformatted dlarray
object with dimensions ordered according to the formats in this table. The formats listed here are only a subset. The layer may support additional formats such as formats with additional "S"
(spatial) or"U"
(unspecified) dimensions.
Input Format | Position Dimension | Output Format |
---|---|---|
"SCB" (spatial, channel, batch) | "auto""spatial" | "SCB" (spatial, channel, batch) |
"CBT" (channel, batch, time) | "auto""temporal" | "CBT" (channel, batch, time) |
"SCBT" (spatial, channel, batch, time) | "auto""temporal""spatial" | "SCBT" (spatial, channel, batch, time) |
"SSCBT" (spatial, spatial, channel, batch, time) | "auto""temporal" | "SSCBT" (spatial, spatial, channel, batch, time) |
"SSSCBT" (spatial, spatial, spatial, channel, batch, time) | "auto""temporal" | "SSSCBT" (spatial, spatial, spatial, channel, batch, time) |
"SC" (spatial, channel) | "auto""spatial" | "SC" (spatial, channel) |
"SB" (spatial, batch) | "auto""spatial" | "SCB" (spatial, channel, batch) |
"SU" (spatial, unspecified) | "auto""spatial" | "SCU" (spatial, channel, unspecified) |
In dlnetwork
objects, PositionEmbeddingLayer
objects also support these input and output format combinations.
Input Format | Position Dimension | Output Format |
---|---|---|
"CT" (channel, time) | "auto""temporal" | "CT" (channel, time) |
"SCT" (spatial, channel, time) | "auto""temporal""spatial" | "SCT" (spatial, channel, time) |
"SSCT" (spatial, spatial, channel, time) | "auto""temporal" | "SSCT" (spatial, spatial, channel, time) |
"SSSCT" (spatial, spatial, spatial, channel, time) | "auto""temporal" | "SSSCT" (spatial, spatial, spatial, channel, time) |
"BT" (batch, time) | "auto""temporal" | "CBT" (channel, batch, time) |
"SBT" (spatial, batch, time) | "auto""temporal""spatial" | "SCBT" (spatial, channel, batch, time) |
"SSBT" (spatial, spatial, batch, time) | "auto""temporal" | "SSCBT" (spatial, spatial, channel, batch, time) |
"SSSBT" (spatial, spatial, spatial, batch, time) | "auto""temporal" | "SSSCBT" (spatial, spatial, spatial, channel, batch, time) |
"ST" (spatial, time) | "auto""temporal""spatial" | "SCT" (spatial, channel, time) |
"SST" (spatial, spatial, time) | "auto""temporal" | "SSCT" (spatial, spatial, channel, time) |
"SSST" (spatial, spatial, spatial, time) | "auto""temporal" | "SSSCT" (spatial, spatial, spatial, channel, time) |
"TU" (time, unspecified) | "auto""temporal" | "CTU" (channel, time, unspecified) |
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
Usage notes and limitations:
You can generate generic C/C++ code that does not depend on third-party libraries and deploy the generated code to hardware platforms.
For code generation, you must pass a dlarray
object with a channel (C) dimension as the input to this layer. For example, code generation supports data format such as "SSC" or "SSCBT".
You can generate CUDA code that is independent of deep learning libraries and deploy the generated code to platforms that use NVIDIA® GPU processors.
For code generation, you must pass a dlarray
object with a channel (C) dimension as the input to this layer. For example, code generation supports data format such as "SSC" or "SSCBT".
Version History
Introduced in R2023b