T5 Architecture Explained & Encoder-Decoder Model Comparison

T5 Example with Pre-training and Fine-tuning
Title: T5 Example with Pre-training and Fine-tuning
Source: Exploring Transfer Learning with T5: the Text-To-Text Transfer Transformer by Google Research

Introduction to T5

T5 (Text-to-Text Transfer Transformer) is a transformer-based Encoder-Decoder model introduced in the paper: Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer by Raffel et al. in 2019. It is designed to handle a wide range of natural language processing (NLP) tasks in a unified framework. The key innovation of T5 is that it treats every NLP problem as a text-to-text task. This design simplifies the framework for multi-task learning and transfer learning in NLP.

T5 Text-to-Text Framework

T5’s text-to-text framework is a key innovation that simplifies natural language processing (NLP) tasks by framing all problems as converting an input text string into an output text string. This unified approach eliminates the need for task-specific architectures for pretraining and fine-tuning, making T5 versatile and straightforward for a wide range of NLP applications. To allow the model to differentiate various tasks, the author added task-specific prefix (a sequence of instruction) to the original input sequence before feeding it to the model. The figure below from the original paper demonstrates the unified framework with task prefix included in model inputs.

A mind map diagram with "T5" in the center, showing examples of different text-to-text tasks. Branches include: translating "That is good." from English to German ("Das ist gut."), classifying a sentence as "not acceptable," rating a sentence with "3.8," summarizing a news report about a storm in Mississippi, and paraphrasing sentences about a rhino grazing in a field.
Title: T5’s Text-to-text Unified Framework Illustration
Source: “Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer” by Raffel et al. 2019.
Each task input contains a task-specific prefix, e.g., “translate English to German: ” for the task of English-to German translation.

Model Architecture

T5 is based heavily on the Transformer architecture introduced by Vaswani et al. (2017). It follows the encoder-decoder structure described in brief as below:

  1. Embedding Layer
    • The model processes the input text, converts it into a sequence of contextualized embeddings, and feeds them into the encoder.
       
  2. Encoder
    • Each layer contains a stack of blocks, each comprising self-attention and feed-forward sublayers.
    • A residual skip connection adds each sublayer’s input to its output.
    • The model applies dropout within the feed-forward network, on the skip connection, on the attention weights, and at the input and output of the entire stack
    • The model applies layer normalization to the output of the dropout layer.
       
  3. Decoder
    • The decoder is similar to the encoder except that it has a block of cross-attention sublayers after the self-attention block that handles the output of the encoder.
    • The self-attention mechanism in the decoder employs an autoregressive approach, restricting the model to attend only to previous outputs.
    • The model passes the output of the final decoder block through a dense layer with a softmax activation, sharing the layer’s weights with the input embedding matrix.
       
Transformer Architecutre Flowchart, with Inputs on the left and Outputs on the right
Title: Transformer’s Architecture
Source: “Attention Is All You Need” by Vaswani et al. (2017).

Although roughly equivalent to the original Transformer, T5 differs in three aspects: simplified layer normalization, layer normalization order, and relative position embeddings.

Simplified Layer Normalization Bias

Layer normalization (LayerNorm) is a technique used to stabilize and accelerate the training of neural networks. It normalizes the activations of a layer by ensuring they have a mean of 0 and a variance of 1 across the features for each input.

Formula for Layer Normalization:

For an input vector $x$ with elements $x_1, x_2, \ldots, x_n$:
$$LayerNorm(x) = \frac{(x-\mu)}{\sqrt{(\sigma^2+\varepsilon)}} \cdot \gamma – \beta$$
Where:

  • $\mu$ is the mean of the input.
  • $\sigma^2$ is the variance of the input.
  • $\varepsilon$ is a small constant added for numerical stability.
  • $ \gamma $ and $\beta$ are learnable parameters for scaling and shifting the normalized values.

LayerNorm operates across the features within each example (row-wise normalization), making it well-suited for sequence models like Transformers. On the other hand, T5 simplifies the standard LayerNorm by removing the additive bias term ($\beta$):

$$\text{LayerNorm}(x) = \frac{(x-\mu)}{\sqrt{(\sigma^2+\varepsilon)}} \cdot \gamma$$

Why Removing the Bias?

  • Reducing the number of learnable parameters, simplifying the model while not negatively impacting performance.
  • Aligning with the goal of making T5 more efficient while retaining strong performance across NLP tasks.

Layer Normalization Order

The original Transformer applies LayerNorm after the attention or feedforward layers (post-normalization):

$x’ = \textit{MultiHeadAttention}(x)$
$y = \textit{LayerNorm}(x + x’)$
$z’ = \textit{FeedForward}(y)$
$z = \textit{LayerNorm}(y + z’)$

Where:

  • $x$ and $y$ represent inputs to the attention and feedforward layers, respectively.
  • Residual connections ($x + x’$ and $y + z’$) are normalized afterward.

However, T5 applies LayerNorm before the attention or feedforward layers (pre-normalization):

$x’ = \mathit{MultiHeadAttention}(\mathit{LayerNorm}(x))$
$y = x + x’$
$z’ = \mathit{FeedForward}(\mathit{LayerNorm}(y))$
$z = y + z’$

Where:

  • T5 first normalizes the input as $\mathit{LayerNorm}(x)$ and $\mathit{LayerNorm}(y)$
  • The residual connections remain unnormalized.

This pre-normalization ensures more stable training and avoids the vanishing gradient issue that can occur in deep Transformer models.

Relative Position Embeddings

Self-attention is inherently order-agnostic, as it operates on sets without considering sequence order, so it’s common practice to include an explicit positional signal in the Transformer architecture. The original Transformer uses a sinusoidal position signal or learned position embeddings, in which position representations of each dimension are absolute. 

Formula of position embeddings (PE) of the original Transformer:

$PE(pos, 2i) = \sin\left( \frac{\text{pos}}{10000^{\frac{2i}{d_{\text{model}}}}} \right)$
 
$PE(pos, 2i+1) = \cos\left( \frac{\text{pos}}{10000^{\frac{2i}{d_{\text{model}}}}} \right)$
 
$\textit{TransformerInput} = \textit{Embedding}(x) + PE$

Where:

  • $x$ = input sequence
  • $pos$ = position of the sequence
  • $i$ = i-th dimension of an embedding vector
  • $d_{\text{model}}$ = embedding length

However, absolute position embeddings encode fixed positions and do not capture the relative relationships between tokens. This can be limiting for tasks where relative position (e.g., token distance) is more important than the absolute position in the sequence. In addition, absolute position embeddings are tied to specific positions within a predefined maximum sequence length. If the model encounters sequences longer than those it was trained on, it struggles because no positional embeddings exist for the new positions. To solve this problem, T5 adopts another encoding technique called relative position embeddings.

Formula of relative position embeddings:

$$\text{Attention}(Q, K, V) = \text{Softmax}\left( \frac{QK^{T}}{\sqrt{d_k}} + R \right) V$$

Where:

  • $R = R(i,j)$ = bias that depends on the relative position distance between token $i$ in $Query$ and $j$ in $Key$

T5 simplifies relative positional embeddings by using relative biases added to attention logits. The model shares these biases across layers but differentiates them by attention heads within a layer. The embeddings are designed for efficiency, with logarithmic range scaling and a cutoff at 128 tokens for direct positional sensitivity, relying on deeper layers to capture larger distances. This approach balances computational efficiency with effective modeling of token relationships.

YouTube video
Self-Attention with Relative Position Representatives – Paper Explained by AI Coffee Break with Letitia

To sum up, T5’s architecture remains fundamentally the same as the original Transformer, with only three exceptions: simplified layer normalization, layer normalization order, and relative position embeddings.

Table comparing T5 and Original Transformer
Title: Main Difference Between T5 and The Original Transformer
Source: “Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer” by Raffel et al. 2019.

Pre-training

The pretraining of T5 follows a text-to-text framework, where all NLP tasks are cast as text generation problems. During pre-training, T5 was trained on a diverse set of tasks to help it generalize well across a wide variety of downstream tasks.

Dataset

T5 was primarily trained on the Colossal Clean Crawled Corpus (C4), a large-scale, high-quality dataset derived from Common Crawl. The C4 dataset was specifically constructed to provide a diverse and comprehensive set of web pages in English, and it was carefully processed to remove noisy, irrelevant, and low-quality data.

Tokenization

T5 uses the SentencePiece tokenization algorithm for preprocessing text. SentencePiece is an unsupervised text tokenizer and detokenizer that is based on a subword units model. It is widely used in various transformer-based models, due to its ability to handle rare words, unknown words, and out-of-vocabulary tokens more effectively than traditional tokenization methods.

Pre-training Objectives

Transfer learning model’s pre-training often requires an objective that doesn’t rely on labels but helps the model learn generalizable knowledge useful for downstream tasks. Early work in transfer learning for NLP used a causal language modeling objective for pre-training and fine-tuning the model’s parameters. However, recent studies have shown that denoising objectives (also known as masked language modeling) yield better performance, and they have since become the standard.

Denoising Objective in T5

In a denoising objective, T5 is trained to predict missing or corrupted tokens in the input. Inspired by BERT’s (Devlin et al. 2018) masked language modeling and word dropout regularization, T5’s text-to-text model used an objective where 15% of the tokens in the input are randomly selected and dropped out. These dropped-out consecutive spans are replaced with a single sentinel token, each of which has a unique ID that does not correspond to any wordpiece in the vocabulary. The model’s task is to predict the entire sequence with missing spans of tokens. The target sequence includes the corrupted spans, separated by sentinel tokens from the input, with a final sentinel token indicating the end of the target sequence. By masking consecutive spans and only predicting the dropped tokens, the computational cost of pre-training can be largely reduced.

A diagram showing how text is processed for a language model task. The original text is “Thank you for inviting me to your party last week.” with “for inviting” and “last” crossed out. The Inputs line reads “Thank you <X> me to your party <Y> week.” The Targets line reads “<X> for inviting <Y> last <Z>.” Arrows point from the removed text in the original sentence to the placeholders in the inputs and targets.
Title: Noised Span Illustration
Source: “Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer” by Raffel et al. 2019

The words “for”, “inviting” and “last” are randomly chosen for corruption. Each consecutive span of corrupted tokens is replaced by a sentinel token that is unique over the example. Since “for” and “inviting” occur consecutively, they are replaced by a single sentinel. The output sequence then consists of the dropped-out spans, delimited by the sentinel tokens used to replace them in the input plus a final sentinel token.

Chart comparing &apos;Denoising Span Corruption&apos; and Mask Language Modeling&apos; on aspects of masking unit, training task, loss calculation, example models, and masking example
Title: Comparing Denoising Span Corruption v.s. Mask Language Modeling
Source: AIML.com Research

Attention Mask

In Transformer-based models, an attention mask is used to control which parts of the input sequence a token should “attend to” during the attention computation. It helps manage padding tokens, sequence boundaries, or any tokens that should be ignored in certain contexts. Likewise, T5 follows almost the same attention mask paradigm of the original Transformer except for that in the decoder.

In the encoder, all entries of a sequence are fully-visible that allows self-attention mechanism to attend them when producing output representations. In contrast, the Transformer decoder uses a causal masking pattern to prevent the model from attending to future tokens. T5 differs in that it considers task prefix in decoder’s masking by preserving the visibility of the prefix tokens. The figure below shows this masking pattern and a schematic of the resulting “prefix language model.”

Using a “prefix LM” has proved effective on a wide variety of text-to-text tasks (Dong et al. 2019). This architecture is similar to an encoder-decoder model with parameters shared across the encoder and decoder and with the encoder-decoder attention replaced with full attention across the input and target sequence. The decoder’s sequence can thus attend to prefix tokens and tokens that come before it in the sequence.

Top row:

Fully-visible: A 5×5 grid where each output token y₁ to y₅ attends to all input tokens x₁ to x₅ (all cells filled).

Causal: A 5×5 grid where each output token attends only to the current and previous input tokens (upper right cells are empty).

Causal with prefix: A 5×5 grid where a fixed prefix portion attends to all inputs, followed by causal masking for the rest.

Bottom row:

Encoder–Decoder model: Green encoder layer processes inputs x₁ to x₄, outputs to a pink decoder layer producing y₁ and y₂.

Language model: Blue stacked layers process interleaved input and output tokens x₂, x₃, y₁, y₂ with causal connections.

Prefix language model: Yellow stacked layers process x₂, x₃, y₁, y₂ with connections showing a fully visible prefix followed by causal attention.
Title: Causal Attention Mask with Prefix
Source: “Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer” by Raffel et al. 2019.

Fine-tuning

Approaches

In T5’s original paper, the author focused on two fine-tuning approaches that update only a subset of the parameters of our encoder-decoder model. Such considerations of parameter efficiency have gained significant attention in the deep learning research field. These approaches can be categorized as “Parameter-efficient Fine-tuning”.  Recent successful research includes LoRA, Prefix Tuning, Prompt Tuning, and QLoRA…etc.

  • Adapter Layers

    Adapter layers (Houlsby et al, 2019) are additional feed-forward networks introduced into the Transformer architecture. Each adapter consists of a dense-ReLU-dense structure, where the output dimension matches the input dimension. This design ensures seamless integration into the existing Transformer without altering its structure or parameters. During fine-tuning, the adapter layers and layer normalization parameters are the ones the model updates, leaving the rest unchanged. The primary hyperparameter for this approach is the inner dimensionality d of the feed-forward network, which determines the number of new parameters added.

    Source: https://arxiv.org/pdf/1902.00751
  • Gradual unfreezing

    Gradual unfreezing (Howard et al, 2018) is a fine-tuning strategy where the model’s parameters are progressively trained in stages. Initially, we fine-tune only the final layer’s parameters. After a set number of updates, we include the second-to-last layer in the training process. This step-by-step addition continues until the process fine-tunes all layers in the model. To adapt this approach to the encoder-decoder T5, the authors gradually unfreeze layers in the encoder and decoder in parallel, starting from the top in both cases. Since the parameters of our input embedding matrix and output classification matrix are shared, we update them throughout fine-tuning.
Diagram showing flowchart of Transformer Layer on the left and Adapter Layer on the right
Title: Adapter Module
Source: “Parameter-Efficient Transfer Learning for NLP” by Houlsby et al, 2019
Diagram showing Gradual Freezing, going from Embedding Layer to Layer 1, Layer 2, Layer 3, and then Softmax layer
Title: Gradual Freezing
Source: “Universal Language Model Fine-tuning for Text Classification” by Howard et al, 2018

Applicable Tasks

T5 is designed to be a highly versatile model that can handle a wide range of NLP tasks by framing them as text-to-text problems. This flexibility allows T5 to be fine-tuned for various applications, making it suitable for numerous scenarios in NLP. Some well-known successful tasks include:

  • Text Summarization: producing a condensed version of a given text .
  • Question Answering: providing accurate and relevant answers to questions.
  • Language Translation: Translating text from one language to another.
  • Text Classification: assigning predefined labels to text.

Transformers-based Model Comparison

Over years, Transformer models have evolved to various derivations. In general, all these derivations can be categorized into encoder-only models, decoder-only models, and encoder-decoder models. The most representative large language models for the three kinds are: BERT for encoder-only models, GPT-2 for decoder only models, and T5 for encoder-decoder models. The table below summarizes the differences among them.

Table comparing T5, BERT, and GPT-2 on aspects of Architecture, Primary Use Case, Pre-training Objective, Position Embedding, Parameter Count, Strengths, Weakness, and Example Models
Title: Transformer-based Model Comparison
Source: AIML.com Research
YouTube video
Transformers, explained by Google Cloud Tech

It is interesting to note that, despite the conceptual comprehensiveness of encoder-decoder models, there is a notable trend toward adopting decoder-only models in various applications. The shift to decoder-only models stems from their simplicity, scalability, and versatility, as they are built on causal language modeling predicting the next token in a sequence which aligns closely with the core objective of language modeling. This single-stack architecture enables efficient training, unified pretraining, and strong performance in few-shot and zero-shot tasks without the need for task-specific architectures. Decoder-only models excel in generating fluent and coherent text, making them ideal for conversational AI, text generation, and general-purpose tasks. While encoder-decoder models handle fine-grained input understanding and structured tasks better, decoder-only models dominate scenarios that require scalability and adaptability across diverse applications.

Encoder-Decoder Model Comparison

When it comes to encoder-decoder architectures, BART is also often highlighted as one of the most notable and widely referenced models. Developed by Facebook (Meta), BART is also an encoder-decoder model designed for sequence-to-sequence tasks. It is pre-trained using a denoising autoencoder objective, where corrupted text is reconstructed, making it effective for tasks like summarization, translation, and text generation. Here’s the comparison with T5:

Choosing between T5 and BART depends on your task and desired output. T5’s unified text-to-text framework is ideal for tasks like translation, summarization, question answering, and text classification. It generalizes well across diverse tasks and is computationally efficient, making it a strong choice for scenarios requiring fine-tuning on smaller datasets or structured prompts.

BART, on the other hand, excels in generation-heavy tasks, such as abstractive summarization, story generation, and text correction, due to its bidirectional encoder and autoregressive decoder. Its pretraining on noisy text makes it robust for tasks involving noise reduction or perturbed inputs. For tasks requiring narrative coherence or handling real-world noisy data, BART might have the edge. Both models are effective, and experimenting with them based on your dataset and performance metrics can help determine the best fit.

Chart comparing T5 and BART on aspects of Pre-training objective, Parameter Size, Task Framework, Tokenization, Strengths, and Use Cases
Title: T5 vs. BART
Source: AIML.com Research

T5 Variants

Some T5’s well-known variants include T5-Base (a general-purpose model), Flan-T5 (optimized for instruction-following tasks), mT5 (designed for multilingual applications), ByT5 (utilizing character-level tokenization), and T5X (intended for large-scale distributed training research). Each variant is tailored to address specific challenges, enabling T5 to excel across diverse NLP tasks and scenarios. The table below provides a comparative overview of these selected T5 variants, showcasing their unique features, strengths, limitations, and primary use cases.

Chart comparing Models in the T5 Family (T5, Flan-T5, mT5, ByT5) on the aspects of Primary Usage, Parameter Size, Strengths, and Limitations
Title: T5’s Family
Source: AIML.com Research

Video Explanation

  • This video explores the T5 large-scale study on Transfer Learning. This paper takes apart many different factors of the Pre-Training then Fine-Tuning pipeline for NLP. This involves Auto-Regressive Language Modeling vs. BERT-Style Masked Language Modeling and XLNet-style shuffling, as well as the impact of dataset composition, size, and how to best use more computation. (Runtime: ~24 mins)
YouTube video
Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer by Connor Shorten (Youtube)

Summary

In conclusion, T5 represents a breakthrough in the field of NLP by presenting a unified framework for a wide array of tasks. Its Transformer-based architecture, pre-training methodology, and text-to-text approach make it a powerful and versatile tool for solving complex language tasks. As a result, T5 has become one of the most influential models in the ongoing evolution of natural language understanding and generation.

  1. What are Transformers? Discuss the evolution, advantages and major breakthroughs in transformer models
  2. Explain the Transformer Architecture (with Examples and Videos)
  3. Making Transformers Work: Scale, Access, Deployment and Ethics

Author: Chen-En Ma

Author

Help us improve this post by suggesting in comments below:

– modifications to the text, and infographics
– video resources that offer clear explanations for this question
– code snippets and case studies relevant to this concept
– online blogs, and research publications that are a “must read” on this topic

Leave the first comment

Partner Ad
Find out all the ways that you can
Contribute