positionEmbeddingLayer
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
creates a position embedding layer and sets the layer
= positionEmbeddingLayer(outputSize
,maxPosition
)OutputSize
and
MaxPosition
properties.
creates a position embedding layer and sets the layer
= positionEmbeddingLayer(outputSize
,maxPosition
,Name=Value
)PositionDimension
, Name
, Parameters and Initialization, and Learning Rate and Regularization properties using one or
more namevalue arguments.
Properties
Position Embedding
OutputSize
— Number of channels in layer output
positive integer
This property is readonly.
Number of channels in the layer output, specified as a positive integer.
Data Types: single
 double
 int8
 int16
 int32
 int64
 uint8
 uint16
 uint32
 uint64
MaxPosition
— Maximum sequence length or spatial index in layer input
positive integer
This property is readonly.
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
PositionDimension
— Dimension of positions to embed
"auto"
(default)  "temporal"
 "spatial"
This property is readonly.
Dimension of positions to embed, specified as one of these values:
"auto"
— For sequence or spatialtemporal input, embed the temporal positions, which is equivalent to using"temporal"
. For 1D 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
WeightsInitializer
— Function to initialize weights
"narrownormal"
(default)  "glorot"
"he"
 "zeros"
 "ones"
 function handle
Function to initialize the weights, specified as one of these values:
"narrownormal"
— 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
Weights
— Learnable weights
[]
(default)  numeric array
Learnable weights, specified as an OutputSize
byMaxPosition
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
WeightLearnRateFactor
— Learning rate factor for weights
1
(default)  nonnegative scalar
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
WeightL2Factor
— L_{2} regularization factor for weights
1 (default)  nonnegative scalar
L_{2} regularization factor for the weights, specified as a nonnegative scalar.
The software multiplies this factor by the global L_{2} regularization factor to determine the L_{2} regularization for the weights in this layer. For example, if WeightL2Factor
is 2
, then the L_{2} regularization for the weights in this layer is twice the global L_{2} regularization factor. You can specify the global L_{2} regularization factor using the trainingOptions
function.
Data Types: single
 double
 int8
 int16
 int32
 int64
 uint8
 uint16
 uint32
 uint64
Layer
Name
— Layer name
""
(default)  character vector  string scalar
NumInputs
— Number of inputs
1
(default)
This property is readonly.
Number of inputs to the layer, returned as 1
. This layer accepts a
single input only.
Data Types: double
InputNames
— Input names
{'in'}
(default)
This property is readonly.
Input names, returned as {'in'}
. This layer accepts a single input
only.
Data Types: cell
NumOutputs
— Number of outputs
1
(default)
This property is readonly.
Number of outputs from the layer, returned as 1
. This layer has a
single output only.
Data Types: double
OutputNames
— Output names
{'out'}
(default)
This property is readonly.
Output names, returned as {'out'}
. This layer has a single output
only.
Data Types: cell
Examples
Create Position Embedding Layer
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: 'narrownormal' 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="wordemb") positionEmbeddingLayer(embeddingOutputSize,maxPosition,Name="posemb"); additionLayer(2,Name="add") selfAttentionLayer(numHeads,numKeyChannels,AttentionMask="causal") fullyConnectedLayer(numWords) softmaxLayer]; net = addLayers(net,layers); net = connectLayers(net,"wordemb","add/in2");
View the neural network architecture.
plot(net) axis off box off
Algorithms
Position Embedding Layer
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 is
Weights(:,p)
, where Weights
is the learnable
embedding weights.
For example:
For vectorsequence data
X
represented by anumChannels
bynumObservations
bynumTimeSteps
array, wherenumChannels
,numObservations
, andnumTimeSteps
are the numbers of channels, observations, and time steps of the input, respectively, the output is aOutputSize
bynumObservations
bynumTimeSteps
arrayY
, where each vector inY(:,:,t)
over the channel dimension isWeights(:,t)
.For 1D image data
X
represented by aheight
bynumChannels
bynumObservations
array, whereheight
,numChannels
, andnumObservations
are the height, number of channels, and number of observations of the input images, respectively, the output is aheight
byOutputSize
bynumObservations
arrayY
, where each vector inY(i,:,:)
over the channel dimension isWeights(:,i)
.For 2D image sequence data
X
represented by aheight
bywidth
bynumChannels
bynumObservations
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
bywidth
byOutputSize
bynumObservations
bynumTimeSteps
arrayY
, where each vector inY(:,:,:,:,t)
over the channel dimension isWeights(:,t)
.
Layer Input and Output Formats
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 formats consist of one or
more of these characters:
"S"
— Spatial"C"
— Channel"B"
— Batch"T"
— Time"U"
— Unspecified
For example, you can describe 2D image data that is represented as a 4D 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 with
dlnetwork
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 a
FunctionLayer
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) 
 "SCB" (spatial, channel, batch) 
"CBT" (channel, batch, time) 
 "CBT" (channel, batch, time) 
"SCBT" (spatial, channel, batch, time) 
 "SCBT" (spatial, channel, batch, time) 
"SSCBT" (spatial, spatial, channel, batch, time) 
 "SSCBT" (spatial, spatial, channel, batch, time) 
"SSSCBT" (spatial, spatial, spatial, channel, batch, time) 
 "SSSCBT" (spatial, spatial, spatial, channel, batch, time)

"SC" (spatial, channel) 
 "SC" (spatial, channel) 
"SB" (spatial, batch) 
 "SCB" (spatial, channel, batch) 
"SU" (spatial, unspecified) 
 "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) 
 "CT" (channel, time) 
"SCT" (spatial, channel, time) 
 "SCT" (spatial, channel, time) 
"SSCT" (spatial, spatial, channel, time) 
 "SSCT" (spatial, spatial, channel, time) 
"SSSCT" (spatial, spatial, spatial, channel, time) 
 "SSSCT" (spatial, spatial, spatial, channel, time) 
"BT" (batch, time) 
 "CBT" (channel, batch, time) 
"SBT" (spatial, batch, time) 
 "SCBT" (spatial, channel, batch, time) 
"SSBT" (spatial, spatial, batch, time) 
 "SSCBT" (spatial, spatial, channel, batch, time) 
"SSSBT" (spatial, spatial, spatial, batch, time) 
 "SSSCBT" (spatial, spatial, spatial, channel, batch,
time) 
"ST" (spatial, time) 
 "SCT" (spatial, channel, time) 
"SST" (spatial, spatial, time) 
 "SSCT" (spatial, spatial, channel, time) 
"SSST" (spatial, spatial, spatial, time) 
 "SSSCT" (spatial, spatial, spatial, channel, time) 
"TU" (time, unspecified) 
 "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 HumanLevel 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
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
You can generate generic C/C++ code that does not depend on thirdparty 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".
GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.
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
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
 América Latina (Español)
 Canada (English)
 United States (English)
Europe
 Belgium (English)
 Denmark (English)
 Deutschland (Deutsch)
 España (Español)
 Finland (English)
 France (Français)
 Ireland (English)
 Italia (Italiano)
 Luxembourg (English)
 Netherlands (English)
 Norway (English)
 Österreich (Deutsch)
 Portugal (English)
 Sweden (English)
 Switzerland
 United Kingdom (English)