Product

Wednesday, 21 February 2024

The Transformer Model

 


We have already familiarized ourselves with the concept of self-attention as implemented by the Transformer attention mechanism for neural machine translation. We will now be shifting our focus to the details of the Transformer architecture itself to discover how self-attention can be implemented without relying on the use of recurrence and convolutions.

In this tutorial, you will discover the network architecture of the Transformer model.

After completing this tutorial, you will know:

  • How the Transformer architecture implements an encoder-decoder structure without recurrence and convolutions 
  • How the Transformer encoder and decoder work 
  • How the Transformer self-attention compares to the use of recurrent and convolutional layers 

Tutorial Overview

This tutorial is divided into three parts; they are:

  • The Transformer Architecture
    • The Encoder
    • The Decoder
  • Sum Up: The Transformer Model
  • Comparison to Recurrent and Convolutional Layers

Prerequisites

For this tutorial, we assume that you are already familiar with:

The Transformer Architecture

The Transformer architecture follows an encoder-decoder structure but does not rely on recurrence and convolutions in order to generate an output. 

The  encoder-decoder structure of the Transformer architecture
Taken from “Attention Is All You Need“

In a nutshell, the task of the encoder, on the left half of the Transformer architecture, is to map an input sequence to a sequence of continuous representations, which is then fed into a decoder. 

The decoder, on the right half of the architecture, receives the output of the encoder together with the decoder output at the previous time step to generate an output sequence.

At each step the model is auto-regressive, consuming the previously generated symbols as additional input when generating the next.

– Attention Is All You Need, 2017.

The Encoder

The encoder block of the Transformer architecture
Taken from “Attention Is All You Need“

The encoder consists of a stack of � = 6 identical layers, where each layer is composed of two sublayers:

  1. The first sublayer implements a multi-head self-attention mechanism. You have seen that the multi-head mechanism implements ℎ heads that receive a (different) linearly projected version of the queries, keys, and values, each to produce ℎ outputs in parallel that are then used to generate a final result. 
  1. The second sublayer is a fully connected feed-forward network consisting of two linear transformations with Rectified Linear Unit (ReLU) activation in between:

FFN(�)=ReLU(�1�+�1)�2+�2

The six layers of the Transformer encoder apply the same linear transformations to all the words in the input sequence, but each layer employs different weight (�1,�2) and bias (�1,�2) parameters to do so. 

Furthermore, each of these two sublayers has a residual connection around it.

Each sublayer is also succeeded by a normalization layer, layernorm(.), which normalizes the sum computed between the sublayer input, �, and the output generated by the sublayer itself, sublayer(�):

layernorm(�+sublayer(�))

An important consideration to keep in mind is that the Transformer architecture cannot inherently capture any information about the relative positions of the words in the sequence since it does not make use of recurrence. This information has to be injected by introducing positional encodings to the input embeddings. 

The positional encoding vectors are of the same dimension as the input embeddings and are generated using sine and cosine functions of different frequencies. Then, they are simply summed to the input embeddings in order to inject the positional information.

The Decoder 

The decoder block of the Transformer architecture
Taken from “Attention Is All You Need“

The decoder shares several similarities with the encoder. 

The decoder also consists of a stack of � = 6 identical layers that are each composed of three sublayers:

  1. The first sublayer receives the previous output of the decoder stack, augments it with positional information, and implements multi-head self-attention over it. While the encoder is designed to attend to all words in the input sequence regardless of their position in the sequence, the decoder is modified to attend only to the preceding words. Hence, the prediction for a word at position � can only depend on the known outputs for the words that come before it in the sequence. In the multi-head attention mechanism (which implements multiple, single attention functions in parallel), this is achieved by introducing a mask over the values produced by the scaled multiplication of matrices � and �. This masking is implemented by suppressing the matrix values that would otherwise correspond to illegal connections:

mask(QK�)=mask([�11�12…�1��21�22…�2�⋮⋮⋱⋮��1��2…���])=[�11−∞…−∞�21�22…−∞⋮⋮⋱⋮��1��2…���]

 

The multi-head attention in the decoder implements several masked, single-attention functions
Taken from “Attention Is All You Need“

The masking makes the decoder unidirectional (unlike the bidirectional encoder).

–  Advanced Deep Learning with Python, 2019.

  1. The second layer implements a multi-head self-attention mechanism similar to the one implemented in the first sublayer of the encoder. On the decoder side, this multi-head mechanism receives the queries from the previous decoder sublayer and the keys and values from the output of the encoder. This allows the decoder to attend to all the words in the input sequence.
  1. The third layer implements a fully connected feed-forward network, similar to the one implemented in the second sublayer of the encoder.

Furthermore, the three sublayers on the decoder side also have residual connections around them and are succeeded by a normalization layer.

Positional encodings are also added to the input embeddings of the decoder in the same manner as previously explained for the encoder. 

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.

Sum Up: The Transformer Model

The Transformer model runs as follows:

  1. Each word forming an input sequence is transformed into a �model-dimensional embedding vector. 
  1. Each embedding vector representing an input word is augmented by summing it (element-wise) to a positional encoding vector of the same �model length, hence introducing positional information into the input. 
  1. The augmented embedding vectors are fed into the encoder block consisting of the two sublayers explained above. Since the encoder attends to all words in the input sequence, irrespective if they precede or succeed the word under consideration, then the Transformer encoder is bidirectional. 
  1. The decoder receives as input its own predicted output word at time-step, �–1.
  1. The input to the decoder is also augmented by positional encoding in the same manner done on the encoder side. 
  1. The augmented decoder input is fed into the three sublayers comprising the decoder block explained above. Masking is applied in the first sublayer in order to stop the decoder from attending to the succeeding words. At the second sublayer, the decoder also receives the output of the encoder, which now allows the decoder to attend to all the words in the input sequence.
  1. The output of the decoder finally passes through a fully connected layer, followed by a softmax layer, to generate a prediction for the next word of the output sequence. 

Comparison to Recurrent and Convolutional Layers

Vaswani et al. (2017) explain that their motivation for abandoning the use of recurrence and convolutions was based on several factors:

  1. Self-attention layers were found to be faster than recurrent layers for shorter sequence lengths and can be restricted to consider only a neighborhood in the input sequence for very long sequence lengths. 
  1. The number of sequential operations required by a recurrent layer is based on the sequence length, whereas this number remains constant for a self-attention layer. 
  1. In convolutional neural networks, the kernel width directly affects the long-term dependencies that can be established between pairs of input and output positions. Tracking long-term dependencies would require using large kernels or stacks of convolutional layers that could increase the computational cost.

Further Reading

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

Books

Papers

Summary

In this tutorial, you discovered the network architecture of the Transformer model.

Specifically, you learned:

  • How the Transformer architecture implements an encoder-decoder structure without recurrence and convolutions
  • How the Transformer encoder and decoder work
  • How the Transformer self-attention compares to recurrent and convolutional layers

Do you have any questions?
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...