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|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""text_summarization_finetune.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1DC3LFNnBCIfmnKp8DvUFF8Q2FIhwc7RP
|
| 8 |
+
|
| 9 |
+
# Text Summarization — Fine-tuning T5-small on CNN/DailyMail
|
| 10 |
+
|
| 11 |
+
**Dataset:** `cnn_dailymail` (v3.0.0) — news articles with human-written highlights (summaries)
|
| 12 |
+
|
| 13 |
+
**Model:** `t5-small` — lightweight encoder-decoder model, good fit for Colab's free GPU
|
| 14 |
+
|
| 15 |
+
**Steps:**
|
| 16 |
+
1. Install libraries
|
| 17 |
+
2. Load & explore dataset
|
| 18 |
+
3. Load tokenizer & model
|
| 19 |
+
4. Preprocess (tokenize) data
|
| 20 |
+
5. Set up training (Seq2SeqTrainer)
|
| 21 |
+
6. Train
|
| 22 |
+
7. Evaluate with ROUGE
|
| 23 |
+
8. Run inference on a custom example
|
| 24 |
+
9. Save & (optionally) push the model
|
| 25 |
+
|
| 26 |
+
> Tip: In Colab go to **Runtime > Change runtime type > T4 GPU** before running.
|
| 27 |
+
|
| 28 |
+
## 1. Install libraries
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
!pip install -q transformers datasets evaluate rouge_score accelerate sentencepiece
|
| 32 |
+
|
| 33 |
+
!pip install -q -U datasets huggingface_hub transformers
|
| 34 |
+
|
| 35 |
+
"""## 2. Load & explore the dataset"""
|
| 36 |
+
|
| 37 |
+
from datasets import load_dataset
|
| 38 |
+
raw_datasets = load_dataset("abisee/cnn_dailymail", "3.0.0")
|
| 39 |
+
|
| 40 |
+
train_dataset = raw_datasets["train"].shuffle(seed=42).select(range(3000))
|
| 41 |
+
val_dataset = raw_datasets["validation"].shuffle(seed=42).select(range(300))
|
| 42 |
+
test_dataset = raw_datasets["test"].shuffle(seed=42).select(range(300))
|
| 43 |
+
|
| 44 |
+
print(train_dataset)
|
| 45 |
+
print(train_dataset[0]["article"][:500])
|
| 46 |
+
print("\n--- Summary ---")
|
| 47 |
+
print(train_dataset[0]["highlights"])
|
| 48 |
+
|
| 49 |
+
"""## 3. Load tokenizer & model"""
|
| 50 |
+
|
| 51 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
| 52 |
+
|
| 53 |
+
model_checkpoint = "t5-small"
|
| 54 |
+
|
| 55 |
+
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
|
| 56 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(model_checkpoint)
|
| 57 |
+
|
| 58 |
+
prefix = "summarize: "
|
| 59 |
+
|
| 60 |
+
"""## 4. Preprocess (tokenize) the data"""
|
| 61 |
+
|
| 62 |
+
max_input_length = 512
|
| 63 |
+
max_target_length = 128
|
| 64 |
+
|
| 65 |
+
def preprocess_function(examples):
|
| 66 |
+
inputs = [prefix + doc for doc in examples["article"]]
|
| 67 |
+
model_inputs = tokenizer(inputs, max_length=max_input_length, truncation=True)
|
| 68 |
+
|
| 69 |
+
labels = tokenizer(text_target=examples["highlights"], max_length=max_target_length, truncation=True)
|
| 70 |
+
|
| 71 |
+
model_inputs["labels"] = labels["input_ids"]
|
| 72 |
+
return model_inputs
|
| 73 |
+
|
| 74 |
+
tokenized_train = train_dataset.map(preprocess_function, batched=True, remove_columns=train_dataset.column_names)
|
| 75 |
+
tokenized_val = val_dataset.map(preprocess_function, batched=True, remove_columns=val_dataset.column_names)
|
| 76 |
+
tokenized_test = test_dataset.map(preprocess_function, batched=True, remove_columns=test_dataset.column_names)
|
| 77 |
+
|
| 78 |
+
"""## 5. Set up training"""
|
| 79 |
+
|
| 80 |
+
import numpy as np
|
| 81 |
+
import evaluate
|
| 82 |
+
from transformers import DataCollatorForSeq2Seq, Seq2SeqTrainingArguments, Seq2SeqTrainer
|
| 83 |
+
|
| 84 |
+
data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=model)
|
| 85 |
+
|
| 86 |
+
rouge = evaluate.load("rouge")
|
| 87 |
+
|
| 88 |
+
def compute_metrics(eval_pred):
|
| 89 |
+
predictions, labels = eval_pred
|
| 90 |
+
decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)
|
| 91 |
+
|
| 92 |
+
labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
|
| 93 |
+
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
|
| 94 |
+
|
| 95 |
+
result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)
|
| 96 |
+
result = {k: round(v * 100, 2) for k, v in result.items()}
|
| 97 |
+
|
| 98 |
+
prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions]
|
| 99 |
+
result["gen_len"] = round(np.mean(prediction_lens), 2)
|
| 100 |
+
return result
|
| 101 |
+
|
| 102 |
+
training_args = Seq2SeqTrainingArguments(
|
| 103 |
+
output_dir="./t5-summarization-cnn",
|
| 104 |
+
eval_strategy="epoch",
|
| 105 |
+
save_strategy="epoch",
|
| 106 |
+
learning_rate=3e-4,
|
| 107 |
+
per_device_train_batch_size=8,
|
| 108 |
+
per_device_eval_batch_size=8,
|
| 109 |
+
weight_decay=0.01,
|
| 110 |
+
save_total_limit=2,
|
| 111 |
+
num_train_epochs=3,
|
| 112 |
+
predict_with_generate=True,
|
| 113 |
+
fp16=True,
|
| 114 |
+
logging_steps=50,
|
| 115 |
+
report_to="none",
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
trainer = Seq2SeqTrainer(
|
| 119 |
+
model=model,
|
| 120 |
+
args=training_args,
|
| 121 |
+
train_dataset=tokenized_train,
|
| 122 |
+
eval_dataset=tokenized_val,
|
| 123 |
+
data_collator=data_collator,
|
| 124 |
+
compute_metrics=compute_metrics,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
"""## 6. Train"""
|
| 128 |
+
|
| 129 |
+
trainer.train()
|
| 130 |
+
|
| 131 |
+
"""## 7. Evaluate on the test set"""
|
| 132 |
+
|
| 133 |
+
test_results = trainer.predict(tokenized_test)
|
| 134 |
+
print(test_results.metrics)
|
| 135 |
+
|
| 136 |
+
"""## 8. Try it on a custom example"""
|
| 137 |
+
|
| 138 |
+
def summarize(text, max_length=128):
|
| 139 |
+
inputs = tokenizer(prefix + text, return_tensors="pt", truncation=True, max_length=max_input_length).to(model.device)
|
| 140 |
+
summary_ids = model.generate(
|
| 141 |
+
**inputs,
|
| 142 |
+
max_length=max_length,
|
| 143 |
+
num_beams=4,
|
| 144 |
+
length_penalty=2.0,
|
| 145 |
+
early_stopping=True,
|
| 146 |
+
)
|
| 147 |
+
return tokenizer.decode(summary_ids[0], skip_special_tokens=True)
|
| 148 |
+
|
| 149 |
+
sample_article = test_dataset[0]["article"]
|
| 150 |
+
print("Original article:\n", sample_article[:800])
|
| 151 |
+
print("\nReference summary:\n", test_dataset[0]["highlights"])
|
| 152 |
+
print("\nModel summary:\n", summarize(sample_article))
|
| 153 |
+
|
| 154 |
+
"""## 9. Save the model (and optionally push to Hugging Face Hub)"""
|
| 155 |
+
|
| 156 |
+
save_dir = "./t5-summarization-cnn-final"
|
| 157 |
+
trainer.save_model(save_dir)
|
| 158 |
+
tokenizer.save_pretrained(save_dir)
|
| 159 |
+
print("Model saved to", save_dir)
|
| 160 |
+
|
| 161 |
+
"""## Notes & next steps
|
| 162 |
+
- **Scaling up:** increase `train_dataset`/`val_dataset` sizes and `num_train_epochs` for better ROUGE scores (full dataset training takes hours even on T4 — good for a final run, not quick iteration).
|
| 163 |
+
- **Bigger model:** swap `t5-small` for `t5-base`, `facebook/bart-base`, or `sshleifer/distilbart-cnn-12-6` if you have more GPU memory/time.
|
| 164 |
+
- **Different domain:** swap the dataset for `samsum` (dialogue summarization) or `xsum` (very short summaries) by changing the `load_dataset(...)` call and the column names (`dialogue`/`summary` for samsum).
|
| 165 |
+
"""
|