Skip to main content

What are transformers in AI? Explain Encoder only (BERT), Decoder only (GPT) and Encoder and Decoder Based (T5) transformers.

Understanding Transformers in AI: Encoder-Only, Decoder-Only, and Encoder-Decoder Architectures

Transformers have revolutionized the field of artificial intelligence (AI), particularly in natural language processing (NLP). Introduced in the paper "Attention is All You Need" by Vaswani et al. in 2017, transformers have become the backbone of modern AI models like BERT, GPT, and T5. In this blog post, we’ll explore what transformers are, how they work, and the differences between encoder-onlydecoder-only, and encoder-decoder architectures.


What Are Transformers?

Transformers are a type of neural network architecture designed to handle sequential data, such as text, without relying on recurrent layers (e.g., RNNs or LSTMs). Instead, they use a mechanism called self-attention to process input data in parallel, making them faster and more efficient for large-scale tasks.

Key Components of Transformers:

  1. Self-Attention Mechanism: Weighs the importance of different words in a sentence relative to each other.

  2. Positional Encoding: Adds information about the position of words in a sequence since transformers don’t process data sequentially.

  3. Feed-Forward Neural Networks: Used to transform the output of the attention layers.

  4. Encoder and Decoder Blocks: The building blocks of transformer architectures.


Types of Transformer Architectures

Transformers can be categorized into three main types based on their architecture:

  1. Encoder-Only Models (e.g., BERT)

  2. Decoder-Only Models (e.g., GPT)

  3. Encoder-Decoder Models (e.g., T5)

Let’s dive into each of these architectures.


1. Encoder-Only Models (e.g., BERT)

Encoder-only models focus on understanding and representing input data. They are primarily used for tasks that require understanding context, such as text classification, named entity recognition, and question answering.

Key Features:

  • Bidirectional Context: Encoder-only models process input data in both directions (left-to-right and right-to-left), allowing them to capture context from the entire sentence.

  • No Generation: These models are not designed to generate text but rather to extract meaningful representations of the input.

Example: BERT (Bidirectional Encoder Representations from Transformers)

BERT is a popular encoder-only model that uses masked language modeling (MLM) to predict missing words in a sentence.

How BERT Works:

  1. Input Representation: BERT takes a sequence of tokens as input and adds positional embeddings.

  2. Masked Language Modeling (MLM): Randomly masks some tokens in the input and predicts them based on the surrounding context.

  3. Output: Produces contextualized embeddings for each token.

Code Example:

python
Copy
from transformers import BertTokenizer, BertForMaskedLM
import torch

# Load pre-trained BERT model and tokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForMaskedLM.from_pretrained('bert-base-uncased')

# Input sentence with a masked token
input_text = "The quick brown [MASK] jumps over the lazy dog."

# Tokenize input
inputs = tokenizer(input_text, return_tensors='pt')

# Predict the masked token
with torch.no_grad():
    outputs = model(**inputs).logits

# Decode the predicted token
predicted_token = torch.argmax(outputs[0, inputs['input_ids'][0] == tokenizer.mask_token_id])
print("Predicted Token:", tokenizer.decode(predicted_token))

2. Decoder-Only Models (e.g., GPT)

Decoder-only models are designed for text generation tasks. They process input data in a unidirectional manner (left-to-right) and are trained to predict the next word in a sequence.

Key Features:

  • Unidirectional Context: These models only consider previous tokens when generating the next token.

  • Autoregressive Generation: They generate text one token at a time, using previously generated tokens as input.

Example: GPT (Generative Pre-trained Transformer)

GPT is a decoder-only model that uses autoregressive language modeling to generate coherent and contextually relevant text.

How GPT Works:

  1. Input Representation: GPT takes a sequence of tokens as input and adds positional embeddings.

  2. Autoregressive Modeling: Predicts the next token in the sequence based on the previous tokens.

  3. Output: Generates text one token at a time.

Code Example:

python
Copy
from transformers import GPT2Tokenizer, GPT2LMHeadModel

# Load pre-trained GPT-2 model and tokenizer
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')

# Input prompt
input_text = "Once upon a time"

# Tokenize input
inputs = tokenizer(input_text, return_tensors='pt')

# Generate text
output = model.generate(inputs['input_ids'], max_length=50, num_return_sequences=1)

# Decode the generated text
generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
print("Generated Text:", generated_text)

3. Encoder-Decoder Models (e.g., T5)

Encoder-decoder models combine both encoder and decoder components, making them suitable for sequence-to-sequence tasks like translation, summarization, and text generation.

Key Features:

  • Bidirectional Encoding: The encoder processes the input sequence bidirectionally.

  • Autoregressive Decoding: The decoder generates the output sequence one token at a time.

  • Versatility: Can handle a wide range of tasks by framing them as text-to-text problems.

Example: T5 (Text-to-Text Transfer Transformer)

T5 is an encoder-decoder model that treats every NLP task as a text-to-text problem, where both the input and output are text strings.

How T5 Works:

  1. Input Representation: The encoder processes the input text bidirectionally.

  2. Task-Specific Prefix: A task-specific prefix (e.g., "translate English to French:") is added to the input.

  3. Output Generation: The decoder generates the output text autoregressively.

Code Example:

python
Copy
from transformers import T5Tokenizer, T5ForConditionalGeneration

# Load pre-trained T5 model and tokenizer
tokenizer = T5Tokenizer.from_pretrained('t5-small')
model = T5ForConditionalGeneration.from_pretrained('t5-small')

# Input text and task prefix
input_text = "translate English to French: The house is wonderful."

# Tokenize input
inputs = tokenizer(input_text, return_tensors='pt')

# Generate translation
output = model.generate(inputs['input_ids'], max_length=50)

# Decode the output
translated_text = tokenizer.decode(output[0], skip_special_tokens=True)
print("Translated Text:", translated_text)

Comparison of Transformer Architectures

FeatureEncoder-Only (BERT)Decoder-Only (GPT)Encoder-Decoder (T5)
ContextBidirectionalUnidirectionalBidirectional (Encoder)
Primary Use CaseUnderstanding contextText generationSequence-to-sequence tasks
Example TasksText classification, Q&AText generation, completionTranslation, summarization
Training ObjectiveMasked language modelingAutoregressive modelingText-to-text generation

Conclusion

Transformers have transformed the field of AI, enabling state-of-the-art performance across a wide range of NLP tasks. Whether you’re working with encoder-only models like BERT for understanding context, decoder-only models like GPT for text generation, or encoder-decoder models like T5 for sequence-to-sequence tasks, transformers provide a powerful and flexible framework for building AI systems.

By understanding the differences between these architectures, you can choose the right model for your specific use case and leverage the full potential of transformers in your projects.


References:

 

Comments

Popular posts from this blog

Simple Linear Regression - and Related Regression Loss Functions

Today's Topics: a. Regression Algorithms  b. Outliers - Explained in Simple Terms c. Common Regression Metrics Explained d. Overfitting and Underfitting e. How are Linear and Non Linear Regression Algorithms used in Neural Networks [Future study topics] Regression Algorithms Regression algorithms are a category of machine learning methods used to predict a continuous numerical value. Linear regression is a simple, powerful, and interpretable algorithm for this type of problem. Quick Example: These are the scores of students vs. the hours they spent studying. Looking at this dataset of student scores and their corresponding study hours, can we determine what score someone might achieve after studying for a random number of hours? Example: From the graph, we can estimate that 4 hours of daily study would result in a score near 80. It is a simple example, but for more complex tasks the underlying concept will be similar. If you understand this graph, you will understand this blog. Sim...

What problems can AI Neural Networks solve

How does AI Neural Networks solve Problems? What problems can AI Neural Networks solve? Based on effectiveness and common usage, here's the ranking from best to least suitable for neural networks (Classification Problems, Regression Problems and Optimization Problems.) But first some Math, background and related topics as how the Neural Network Learn by training (Supervised Learning and Unsupervised Learning.)  Background Note - Mathematical Precision vs. Practical AI Solutions. Math can solve all these problems with very accurate results. While Math can theoretically solve classification, regression, and optimization problems with perfect accuracy, such calculations often require impractical amounts of time—hours, days, or even years for complex real-world scenarios. In practice, we rarely need absolute precision; instead, we need actionable results quickly enough to make timely decisions. Neural networks excel at this trade-off, providing "good enough" solutions in seco...

Activation Functions in Neural Networks

  A Guide to Activation Functions in Neural Networks 🧠 Question: Without activation function can a neural network with many layers be non-linear? Answer: Provided at the end of this document. Activation functions are a crucial component of neural networks. Their primary purpose is to introduce non-linearity , which allows the network to learn the complex, winding patterns found in real-world data. Without them, a neural network, no matter how deep, would just be a simple linear model. In the diagram below the f is the activation function that receives input and send output to next layers. Commonly used activation functions. 1. Sigmoid Function 2. Tanh (Hyperbolic Tangent) 3. ReLU (Rectified Linear Unit - Like an Electronic Diode) 4. Leaky ReLU & PReLU 5. ELU (Exponential Linear Unit) 6. Softmax 7. GELU, Swish, and SiLU 1. Sigmoid Function                       The classic "S-curve," Sigmoid squashes any input value t...