Use the offer code 20offearlybird to get 20% off.

# The Transformer Positional Encoding Layer in Keras, Part 2

Last Updated on January 6, 2023

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 could implement this layer and its functions yourself in Python. In this tutorial, you’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.

Kick-start your project with my book Building Transformer Models with Attention. It provides self-study tutorials with working code to guide you into building a fully-working transformer model that can
translate sentences from one language to another...

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 three 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

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

1. I am a robot
2. you too robot

Note the text has already been converted to lowercase with all the punctuation marks and noise in the text removed. Next, 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 an 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 the text.

### Want to Get Started With Building Transformer Models with Attention?

Take my free 12-day email crash course now (with sample code).

Click to sign-up and also get a free PDF Ebook version of the course.

## 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, you 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 the vectorized_text to tensors.

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

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

### The Position Embeddings

You 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

### 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 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 to 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:
\begin{eqnarray}
P(k, 2i) &=& \sin\Big(\frac{k}{n^{2i/d}}\Big)\\
P(k, 2i+1) &=& \cos\Big(\frac{k}{n^{2i/d}}\Big)
\end{eqnarray}
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

The embedding from the fixed weights layer are visualized below.

Embedding using sinusoidal positional encoding

You 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 tunable or fixed-weight implementations for your particular application.

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

## Summary

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

## Learn Transformers and Attention!

...using transformer models with attention

Discover how in my new Ebook:
Building Transformer Models with Attention

It provides self-study tutorials with working code to guide you into building a fully-working transformer models that can
translate sentences from one language to another...

### 12 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!

2. Pablo V. October 7, 2022 at 7:11 pm #

Hi James, amazing post, web and content, congratulations. About transformers, I’m being introduced in this new world, understanding it is not being too difficult, but I’ve seen that every single example is always focused on NLP, in the case I would like to use a transformer for time series, shouldn’t I use a special positional encoding layer for this purpose? I mean, I know that the time data can be encoded using sin and cos in data preparation preprocess, before feeding our net with this data time data, but, it is necessary a positional encoding if I want to keep the position of every single element during the time sequence?
Thanks again.

3. Jack October 14, 2022 at 6:42 pm #

Hi Dear Mehreen Saeed

when I study this blog. it show cannot import name ‘TextVectorization’ from ‘tensorflow.keras.layers’. how to fix this error?

thank you.

4. HZ November 8, 2022 at 11:44 am #

Great tutorial! I have a question about the PositionEmbeddingFixedWeights class. Why are you setting word_embedding_matrix equal to get_position_embedding instead of randomly initializing it? Thanks!

• James Carmichael November 9, 2022 at 7:33 am #

Hi HZ…You are very welcome! The setting was for illustration purposes only. A random initialization is actually a preferred method. Please pursue your suggestion and let us know what you find!

5. Diego November 20, 2022 at 8:46 pm #

The Position Embedding layer in this blog, that’s not the same as the sine/cosine function we build in part 1 right? We now use the same method to generate embeddings as the word embeddings?

6. Diego November 20, 2022 at 8:59 pm #

nevermind my previous comment, I did not check the rest of the tutorial and see that it alreayd follows with sine/cosine-based positional encoding

• James Carmichael November 21, 2022 at 9:36 am #

Thank you the for the update Diego!

7. Serkan January 25, 2023 at 11:14 pm #

Do we need positional encoding in order to use transformer in Time-series forecasting tasks as we pass it to transformer model without breaking its sorted time-series nature?

8. Ivan March 5, 2023 at 12:18 pm #

Hello authors,

Thank you for your efforts with the book.
Could you please explain why word_embeddings set as non-trainable across the whole book ? (my question is not about positional encoding)