πŸ€– AI/ML

T5

Text-to-Text Transfer Transformer

Google's innovative Transformer model that unified all NLP tasks into a "text input -> text output" format. Handles tasks such as translation, summarization, QA, and classification in a single framework.

πŸ“– Detailed Explanation

T5 (Text-to-Text Transfer Transformer) is a large-scale language model announced by Google Research in 2019. The core idea of T5 is to unify all NLP tasks into a text-to-text format. For example, translation is expressed as "translate English to German: Hello" -> "Hallo", and sentiment analysis as "sentiment: This movie is great" -> "positive". With this unified approach, a single model can perform dozens of NLP tasks.

T5 was introduced in the paper "Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer". The Google research team built a 750GB dataset called C4 (Colossal Clean Crawled Corpus) and systematically compared various pre-training methods, model sizes, and training strategies in experiments. This research made an important contribution to the development of transfer learning in the NLP field.

T5 uses an encoder-decoder Transformer architecture. The input text is processed by the encoder, and the decoder generates the output text. Pre-training is carried out using the span corruption method - some spans of the input text are masked, and the model is trained to predict them. Model sizes range from Small (60M) to 11B parameters, and performance improves with size.

T5 is an important milestone in LLM research. FLAN-T5, UL2, PaLM, and others that appeared afterward developed the ideas of T5. In practice, T5 is widely used for summarization, translation, and QA systems, and it is easily accessible through Hugging Face. In particular, its fine-tuning efficiency is good, making it suitable for domain-specific tasks.

πŸ’» Code Example

This is an example of using T5 with Hugging Face Transformers.

# T5 λͺ¨λΈ ν™œμš© 예제
from transformers import T5Tokenizer, T5ForConditionalGeneration
import torch

# λͺ¨λΈ 및 ν† ν¬λ‚˜μ΄μ € λ‘œλ“œ (t5-small, t5-base, t5-large, t5-3b, t5-11b)
model_name = "t5-base"
tokenizer = T5Tokenizer.from_pretrained(model_name)
model = T5ForConditionalGeneration.from_pretrained(model_name)

def generate_text(input_text: str, max_length: int = 128) -> str:
    """T5둜 ν…μŠ€νŠΈ 생성"""
    input_ids = tokenizer.encode(input_text, return_tensors="pt")

    outputs = model.generate(
        input_ids,
        max_length=max_length,
        num_beams=4,
        early_stopping=True,
        no_repeat_ngram_size=2
    )

    return tokenizer.decode(outputs[0], skip_special_tokens=True)

# ===== 1. λ²ˆμ—­ (Translation) =====
print("=" * 50)
print("1. λ²ˆμ—­ (Translation)")
print("=" * 50)

en_to_de = "translate English to German: The house is wonderful."
de_result = generate_text(en_to_de)
print(f"μž…λ ₯: {en_to_de}")
print(f"좜λ ₯: {de_result}")

en_to_fr = "translate English to French: Machine learning is fascinating."
fr_result = generate_text(en_to_fr)
print(f"\nμž…λ ₯: {en_to_fr}")
print(f"좜λ ₯: {fr_result}")

# ===== 2. μš”μ•½ (Summarization) =====
print("\n" + "=" * 50)
print("2. μš”μ•½ (Summarization)")
print("=" * 50)

article = """
summarize: The Amazon rainforest produces about 20% of the world's oxygen
and contains 10% of all species on Earth. Climate change and deforestation
pose serious threats to this vital ecosystem. Scientists warn that losing
the Amazon could accelerate global warming significantly. Conservation
efforts are critical for the planet's future.
"""
summary = generate_text(article, max_length=64)
print(f"원문: {article.strip()}")
print(f"μš”μ•½: {summary}")

# ===== 3. 문법 ꡐ정 (Grammar Correction) =====
print("\n" + "=" * 50)
print("3. 문법 ꡐ정 (Grammar Correction)")
print("=" * 50)

# FLAN-T5 λ˜λŠ” νŒŒμΈνŠœλ‹λœ λͺ¨λΈμ—μ„œ 더 쒋은 κ²°κ³Ό
grammar_input = "cola sentence: He don't knows nothing about it."
corrected = generate_text(grammar_input)
print(f"μž…λ ₯: {grammar_input}")
print(f"좜λ ₯: {corrected}")

# ===== 4. 질문 λ‹΅λ³€ (Question Answering) =====
print("\n" + "=" * 50)
print("4. 질문 λ‹΅λ³€ (Question Answering)")
print("=" * 50)

qa_input = """
question: What is the capital of France?
context: France is a country in Western Europe. Its capital city is Paris,
which is known for the Eiffel Tower and the Louvre Museum.
"""
answer = generate_text(qa_input, max_length=32)
print(f"질문 & μ»¨ν…μŠ€νŠΈ: {qa_input.strip()}")
print(f"λ‹΅λ³€: {answer}")

# ===== 5. FLAN-T5 (ν–₯μƒλœ 버전) =====
print("\n" + "=" * 50)
print("5. FLAN-T5 (Instruction-tuned)")
print("=" * 50)

# FLAN-T5λŠ” instruction following이 더 μ’‹μŒ
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM

flan_model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-base")
flan_tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-base")

def flan_generate(prompt: str) -> str:
    inputs = flan_tokenizer(prompt, return_tensors="pt")
    outputs = flan_model.generate(**inputs, max_length=100)
    return flan_tokenizer.decode(outputs[0], skip_special_tokens=True)

instruction = "Explain what machine learning is in simple terms."
response = flan_generate(instruction)
print(f"질문: {instruction}")
print(f"λ‹΅λ³€: {response}")

πŸ“Š Performance & Cost

T5 Specs by Model Size

Model Parameter Encoder/Decoder VRAM Requirements Main use
T5-Small 60M 6/6 layers ~1GB Experiments, edge devices
T5-Base 220M 12/12 layers ~2GB General-purpose, fast inference
T5-Large 770M 24/24 layers ~4GB High-quality summarization/translation
T5-3B 3B 24/24 layers ~12GB Production NLP
T5-11B 11B 24/24 layers ~45GB Research/top performance

* FLAN-T5: Instruction-tuned version, with better zero-shot performance at the same size
* Free to use on Hugging Face, no commercial API (self-hosting required)

πŸ—£οΈ Say It Like This in Practice

πŸ’¬ In a Meeting
"I'm considering adopting a summarization model, and it would be good to start with T5-base. It's lightweight at 220M parameters, and for Korean we'd have to use mT5, but the quality may be lower than for English. FLAN-T5 has better instruction following, so let's compare them."
πŸ’¬ In an Interview
"The core innovation of T5 is the text-to-text framework. Classification, generation, and QA are all handled the same way, so multi-task learning comes naturally. GPT uses only the decoder, but T5 is an encoder-decoder, so it's better suited to conditional generation tasks."
πŸ’¬ In a Technical Discussion
"When fine-tuning T5, try the prefix approach. If you attach a task prefix like 'summarize:' or 'translate English to Korean:', a single model can handle multiple tasks. Applying LoRA also saves memory."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Common Mistakes & Cautions

❌
Using T5 for Korean
The base T5 was trained mainly on English, so its Korean performance is low. For Korean tasks, use the mT5 (multilingual) or KE-T5 (Korean-specialized) model.
❌
Using T5 for chat/conversation
T5 is optimized for single-turn tasks. If you need multi-turn conversation or long context retention, GPT-family models or LLaMA are more suitable.
βœ…
The right approach
1) Use T5 for tasks with clear inputs and outputs, such as summarization/translation/QA, 2) secure zero-shot performance with FLAN-T5, 3) fine-tune for domain specialization, 4) apply quantization (INT8) when a large model is needed.

πŸ”— Related Terms

πŸ“š Learn More