Product

Wednesday, 21 February 2024

A Gentle Introduction to Positional Encoding in Transformer Models, Part 1

 In languages, the order of the words and their position in a sentence really matters. The meaning of the entire sentence can change if the words are re-ordered. When implementing NLP solutions, recurrent neural networks have an inbuilt mechanism that deals with the order of sequences. The transformer model, however, does not use recurrence or convolution and treats each data point as independent of the other. Hence, positional information is added to the model explicitly to retain the information regarding the order of words in a sentence. Positional encoding is the scheme through which the knowledge of the order of objects in a sequence is maintained.

For this tutorial, we’ll simplify the notations used in this remarkable paper, Attention Is All You Need by Vaswani et al. After completing this tutorial, you will know:

  • What is positional encoding, and why it’s important
  • Positional encoding in transformers
  • Code and visualize a positional encoding matrix in Python using NumPyTutorial Overview

This tutorial is divided into four parts; they are:

  1. What is positional encoding
  2. Mathematics behind positional encoding in transformers
  3. Implementing the positional encoding matrix using NumPy
  4. Understanding and visualizing the positional encoding matrix

What Is Positional Encoding?

Positional encoding describes the location or position of an entity in a sequence so that each position is assigned a unique representation. There are many reasons why a single number, such as the index value, is not used to represent an item’s position in transformer models. For long sequences, the indices can grow large in magnitude. If you normalize the index value to lie between 0 and 1, it can create problems for variable length sequences as they would be normalized differently.

Transformers use a smart positional encoding scheme, where each position/index is mapped to a vector. Hence, the output of the positional encoding layer is a matrix, where each row of the matrix represents an encoded object of the sequence summed with its positional information. An example of the matrix that encodes only the positional information is shown in the figure below.

A Quick Run-Through of the Trigonometric Sine Function

This is a quick recap of sine functions; you can work equivalently with cosine functions. The function’s range is [-1,+1]. The frequency of this waveform is the number of cycles completed in one second. The wavelength is the distance over which the waveform repeats itself. The wavelength and frequency for different waveforms are shown below:


Positional Encoding Layer in Transformers

Let’s dive straight into this. Suppose you have an input sequence of length � and require the position of the ��ℎ object within this sequence. The positional encoding is given by sine and cosine functions of varying frequencies:

�(�,2�)=sin⁡(��2�/�)�(�,2�+1)=cos⁡(��2�/�)

Here:

�: Position of an object in the input sequence, 0≤�<�/2

�: Dimension of the output embedding space

�(�,�): Position function for mapping a position � in the input sequence to index (�,�) of the positional matrix

�: User-defined scalar, set to 10,000 by the authors of Attention Is All You Need.

�: Used for mapping to column indices 0≤�<�/2, with a single value of � maps to both sine and cosine functions

In the above expression, you can see that even positions correspond to a sine function and odd positions correspond to cosine functions.

Example

To understand the above expression, let’s take an example of the phrase “I am a robot,” with n=100 and d=4. The following table shows the positional encoding matrix for this phrase. In fact, the positional encoding matrix would be the same for any four-letter phrase with n=100 and d=4.

Coding the Positional Encoding Matrix from Scratch

Here is a short Python code to implement positional encoding using NumPy. The code is simplified to make the understanding of positional encoding easier.

Understanding the Positional Encoding Matrix

To understand the positional encoding, let’s start by looking at the sine wave for different positions with n=10,000 and d=512.

The following figure is the output of the above code:

Sine wave for different position indices

You can see that each position � corresponds to a different sinusoid, which encodes a single position into a vector. If you look closely at the positional encoding function, you can see that the wavelength for a fixed � is given by:

��=2��2�/�

Hence, the wavelengths of the sinusoids form a geometric progression and vary from 2� to 2��. The scheme for positional encoding has a number of advantages.

  1. The sine and cosine functions have values in [-1, 1], which keeps the values of the positional encoding matrix in a normalized range.
  2. As the sinusoid for each position is different, you have a unique way of encoding each position.
  3. You have a way of measuring or quantifying the similarity between different positions, hence enabling you to encode the relative positions of words.

Visualizing the Positional Matrix

Let’s visualize the positional matrix on bigger values. Use Python’s matshow() method from the matplotlib library. Setting n=10,000 as done in the original paper, you get the following:

The positional encoding matrix for n=10,000, d=512, sequence length=100

What Is the Final Output of the Positional Encoding Layer?

The positional encoding layer sums the positional vector with the word encoding and outputs this matrix for the subsequent layers. The entire process is shown below.

The positional encoding layer in the transformer

Further Reading

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

Books

Papers

Articles

Summary

In this tutorial, you discovered positional encoding in transformers.

Specifically, you learned:

  • What is positional encoding, and why it is needed.
  • How to implement positional encoding in Python using NumPy
  • How to visualize the positional encoding matrix

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.

No comments:

Post a Comment

Payment of ₹1000 requested by HONEY VIG. Click the link to pay securely via Razorpay: Make 5000 payment
Connect broadband

AI:Create a frameworks using various humanoid robotics with the help of various neural networks and LLMs on the occasiun of Diwali night from late night to peak hours to earley morning detection of fireworks reside, the pollution noice, voice and various traces of scraps found there along with fire broken and taming calming the fire broken in real time in the various neural networks of remote backward areas tow, cities, states countries and continents of the US,UK, Canada, Midle East, Africa, Korea, China, Europe, Asia and Oceania in real time. IoT-Based Automated Fire Detection and Alert System Overview This project automates fire detection and alert systems using IoT technology. It replaces traditional methods of fire reporting, ensuring quick and reliable emergency responses even in the absence of human intervention. The system leverages NodeMCU microcontrollers, environmental sensors, and the MQTT protocol to monitor conditions and trigger alarms in case of abnormalities. Features Automated Fire Detection: Monitors temperature and gas levels using DHT11 and gas sensors. Real-Time Alerts: Sends location-based notifications to receivers for immediate action. Scalable MQTT Communication: Efficient communication using a single MQTT topic for all nodes. Localized Alarm System: Receiver nodes trigger buzzers for the corresponding locations. System Architecture Source Nodes: NodeMCUs (Source_Beleghata, Source_London) equipped with: DHT11 Sensor for temperature monitoring. Gas Sensor for detecting smoke or hazardous gases. Publishes location-based messages upon detecting abnormal conditions. Receiver Nodes: NodeMCUs (Receiver_Beleghata, Receiver_London) equipped with buzzers. Subscribes to a shared MQTT topic and triggers the buzzer if the location matches incoming data. Communication Protocol MQTT Protocol: All nodes are connected to the internet for real-time communication. A shared MQTT topic ensures scalability and simplicity. Demonstration Setup Nodes: Source_Beleghata (with sensors) Receiver_Beleghata (with buzzer) Source_London (with sensors) Receiver_London (with buzzer) Workflow: Source nodes detect abnormal conditions and publish the affected location ("Beleghata" or "London") to the MQTT topic. Receiver nodes subscribe to the topic and trigger an alarm if the message matches their location. Requirements Hardware: 4 NodeMCU boards DHT11 sensors (2 units) Gas sensors (2 units) Buzzers (2 units) Software: Arduino IDE MQTT broker (e.g., Mosquitto) Internet connection for NodeMCU devices Installation and Usage Hardware Setup: Connect sensors to the Source NodeMCUs. Connect buzzers to the Receiver NodeMCUs. Software Configuration: Flash the provided code onto the NodeMCU devices using the Arduino IDE. Set up an MQTT broker and configure the nodes to publish/subscribe to the shared topic. Testing: Simulate abnormal conditions to test the system. Verify that alarms are triggered at the appropriate receiver nodes. Future Enhancements Integration with mobile applications for remote monitoring and alerts. Expansion to support additional locations and sensors. Advanced machine learning algorithms for anomaly detection.

  Global AI–IoT Humanoid Robotics Framework for Diwali Night Fireworks, Pollution, Waste and Fire Emergency Detection Proposed...