The Transformer Positional Encoding Layer in Keras, Part 2

In part 1: A gentle introduction to positional encoding in transformer models, we discussed the positional encoding layer of the transformer model. We also showed how you can implement this layer and its functions yourself in Python. In this tutorial, we’ll implement the positional encoding layer in Keras and Tensorflow. You can then use this layer in a complete transformer model.

After completing this tutorial, you will know:

  • Text vectorization in Keras
  • Embedding layer in Keras
  • How to subclass the embedding layer and write your own positional encoding layer.

Let’s get started.

The Transformer Positional Encoding Layer in Keras, Part 2.
Photo by Ijaz Rafi. Some rights reserved

Tutorial Overview

This tutorial is divided into 3 parts; they are:

  1. Text vectorization and embedding layer in Keras
  2. Writing your own positional encoding layer in Keras
    1. Randomly initialized and tunable embeddings
    2. Fixed weight embeddings from Attention is All You Need
  3. Graphical view of the output of the positional encoding layer

The Import Section

First let’s write the section to import all the required libraries:

The Text Vectorization Layer

We’ll start with a set of English phrases, which are already preprocessed and cleaned. The text vectorization layer creates a dictionary of words and replaces each word by its corresponding index in the dictionary. Let’s see how we can map these two sentences using the text vectorization layer:

  1. I am a robot
  2. you too robot

Note we have already converted the text to lowercase and removed all the punctuations and noise in text. We’ll convert these two phrases to vectors of a fixed length 5. The TextVectorization layer of Keras requires a maximum vocabulary size and the required length of output sequence for initialization. The output of the layer is a tensor of shape:

(number of sentences, output sequence length)

The following code snippet uses the adapt method to generate a vocabulary. It next creates a vectorized representation of text.

The Embedding Layer

The Keras Embedding layer converts integers to dense vectors. This layer maps these integers to random numbers, which are later tuned during the training phase. However, you also have the option to set the mapping to some predefined weight values (shown later). To initialize this layer, we need to specify the maximum value of an integer to map, along with the length of the output sequence.

The Word Embeddings

Let’s see how the layer converts our vectorized_text to tensors.

I have annotated the output with my comments as shown below. Note, you will see a different output every time you run this code because the weights have been initialized randomly.

Word embeddings.

Word Embeddings. This output will be different every time you run the code because of the random numbers involved.

The Position Embeddings

We also need the embeddings for the corresponding positions. The maximum positions correspond to the output sequence length of the TextVectorization layer.

The output is shown below:

Position Indices Embedding.

Position Indices Embedding.

The Output of Positional Encoding Layer in Transformers

In a transformer model the final output is the sum of both the word embeddings and the position embeddings. Hence, when you set up both embedding layers, you need to make sure that the output_length is the same for both.

The output is shown below, annotated with my comments. Again, this will be different from your run of the code because of the random weight initialization.

The Final Output After Adding Word Embedding and Position Embedding

SubClassing the Keras Embedding Layer

When implementing a transformer model, you’ll have to write your own position encoding layer. This is quite simple as the basic functionality is already provided for you. This Keras example shows how you can subclass the Embedding layer to implement your own functionality. You can add more methods to it as you require.

Let’s run this layer.

Positional Encoding in Transformers: Attention is All You Need

Note, the above class creates an embedding layer that has trainable weights. Hence, the weights are initialized randomly and tuned in the training phase.
The authors of Attention is All You Need have specified a positional encoding scheme as shown below. You can read the full details in part 1 of this tutorial:
P(k, 2i) &=& \sin\Big(\frac{k}{n^{2i/d}}\Big)\\
P(k, 2i+1) &=& \cos\Big(\frac{k}{n^{2i/d}}\Big)
If you want to use the same positional encoding scheme, you can specify your own embedding matrix as discussed in part 1, which shows how to create your own embeddings in NumPy. When specifying the Embedding layer, you need to provide the positional encoding matrix as weights along with trainable=False. Let’s create another positional embedding class that does exactly this.

Next, we set up everything to run this layer.

Visualizing the Final Embedding

In order to visualize the embeddings, let’s take two bigger sentences, one technical and the other one just a quote. We’ll set up the TextVectorization layer along with the positional encoding layer and see what the final output looks like.

Now let’s see what the random embeddings look like for both phrases.

Random embeddings

Random Embeddings


The embedding from the fixed weights layer are visualized below.

Embedding using sinusoidal positional encoding

Embedding using sinusoidal positional encoding

We can see that the embedding layer initialized using the default parameter outputs random values. On the other hand, the fixed weights generated using sinusoids create a unique signature for every phrase with information on each word position encoded within it.

You can experiment with both tunable or fixed weight implementations for your particular application.

Further Reading

This section provides more resources on the topic if you are looking to go deeper.





In this tutorial, you discovered the implementation of positional encoding layer in Keras.

Specifically, you learned:

  • Text vectorization layer in Keras
  • Positional encoding layer in Keras
  • Creating your own class for positional encoding
  • Setting your own weights for the positional encoding layer in Keras

Do you have any questions about positional encoding discussed in this post? Ask your questions in the comments below and I will do my best to answer.

, , ,

2 Responses to The Transformer Positional Encoding Layer in Keras, Part 2

  1. Guydo May 16, 2022 at 9:40 am #

    Thanks for the super clear and useful explanation!

    • James Carmichael May 17, 2022 at 9:52 am #

      Great feedback Guydo!

Leave a Reply