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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""summarzeit.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colaboratory.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1yB3_W571VKNsjapwX0VKe41YaJkAd60u
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
!pip install transformers[sentencepiece] datasets sacrebleu rouge_score py7zr -q
|
| 11 |
+
|
| 12 |
+
!nvidia-smi
|
| 13 |
+
|
| 14 |
+
from transformers import pipeline, set_seed
|
| 15 |
+
|
| 16 |
+
import matplotlib.pyplot as plt
|
| 17 |
+
from datasets import load_dataset
|
| 18 |
+
import pandas as pd
|
| 19 |
+
from datasets import load_dataset, load_metric
|
| 20 |
+
|
| 21 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 22 |
+
|
| 23 |
+
import nltk
|
| 24 |
+
from nltk.tokenize import sent_tokenize
|
| 25 |
+
|
| 26 |
+
from tqdm import tqdm
|
| 27 |
+
import torch
|
| 28 |
+
|
| 29 |
+
nltk.download("punkt")
|
| 30 |
+
|
| 31 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 32 |
+
|
| 33 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 34 |
+
|
| 35 |
+
model_ckpt = "slauw87/bart_summarisation"
|
| 36 |
+
|
| 37 |
+
tokenizer = AutoTokenizer.from_pretrained(model_ckpt)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
model_pegasus = AutoModelForSeq2SeqLM.from_pretrained(model_ckpt).to(device)
|
| 41 |
+
|
| 42 |
+
def generate_batch_sized_chunks(list_of_elements, batch_size):
|
| 43 |
+
"""split the dataset into smaller batches that we can process simultaneously
|
| 44 |
+
Yield successive batch-sized chunks from list_of_elements."""
|
| 45 |
+
for i in range(0, len(list_of_elements), batch_size):
|
| 46 |
+
yield list_of_elements[i : i + batch_size]
|
| 47 |
+
|
| 48 |
+
def calculate_metric_on_test_ds(dataset, metric, model, tokenizer,
|
| 49 |
+
batch_size=16, device=device,
|
| 50 |
+
column_text="article",
|
| 51 |
+
column_summary="highlights"):
|
| 52 |
+
article_batches = list(generate_batch_sized_chunks(dataset[column_text], batch_size))
|
| 53 |
+
target_batches = list(generate_batch_sized_chunks(dataset[column_summary], batch_size))
|
| 54 |
+
|
| 55 |
+
for article_batch, target_batch in tqdm(
|
| 56 |
+
zip(article_batches, target_batches), total=len(article_batches)):
|
| 57 |
+
|
| 58 |
+
inputs = tokenizer(article_batch, max_length=1024, truncation=True,
|
| 59 |
+
padding="max_length", return_tensors="pt")
|
| 60 |
+
|
| 61 |
+
summaries = model.generate(input_ids=inputs["input_ids"].to(device),
|
| 62 |
+
attention_mask=inputs["attention_mask"].to(device),
|
| 63 |
+
length_penalty=0.8, num_beams=8, max_length=128)
|
| 64 |
+
''' parameter for length penalty ensures that the model does not generate sequences that are too long. '''
|
| 65 |
+
|
| 66 |
+
# Finally, we decode the generated texts,
|
| 67 |
+
# replace the token, and add the decoded texts with the references to the metric.
|
| 68 |
+
decoded_summaries = [tokenizer.decode(s, skip_special_tokens=True,
|
| 69 |
+
clean_up_tokenization_spaces=True)
|
| 70 |
+
for s in summaries]
|
| 71 |
+
|
| 72 |
+
decoded_summaries = [d.replace("", " ") for d in decoded_summaries]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
metric.add_batch(predictions=decoded_summaries, references=target_batch)
|
| 76 |
+
|
| 77 |
+
# Finally compute and return the ROUGE scores.
|
| 78 |
+
score = metric.compute()
|
| 79 |
+
return score
|
| 80 |
+
|
| 81 |
+
dataset_samsum = load_dataset("samsum")
|
| 82 |
+
|
| 83 |
+
split_lengths = [len(dataset_samsum[split])for split in dataset_samsum]
|
| 84 |
+
|
| 85 |
+
print(f"Split lengths: {split_lengths}")
|
| 86 |
+
print(f"Features: {dataset_samsum['train'].column_names}")
|
| 87 |
+
print("\nDocument:")
|
| 88 |
+
|
| 89 |
+
print(dataset_samsum["test"][1]["dialogue"])
|
| 90 |
+
|
| 91 |
+
print("\nSummary:")
|
| 92 |
+
|
| 93 |
+
print(dataset_samsum["test"][1]["summary"])
|
| 94 |
+
|
| 95 |
+
pipe = pipeline('summarization', model = model_ckpt )
|
| 96 |
+
pipe_out = pipe(dataset_samsum["test"][0]["dialogue"])
|
| 97 |
+
|
| 98 |
+
print(pipe_out)
|
| 99 |
+
|
| 100 |
+
print(pipe_out[0]['summary_text'].replace(" .", ".\n"))
|
| 101 |
+
|
| 102 |
+
rouge_metric = load_metric('rouge')
|
| 103 |
+
|
| 104 |
+
score = calculate_metric_on_test_ds(dataset_samsum['test'], rouge_metric, model_pegasus, tokenizer, column_text = 'dialogue', column_summary = 'summary', batch_size = 8)
|
| 105 |
+
|
| 106 |
+
rouge_names = ["rouge1", "rouge2", "rougeL", "rougeLsum"]
|
| 107 |
+
rouge_dict = dict((rn, score[rn].mid.fmeasure ) for rn in rouge_names )
|
| 108 |
+
|
| 109 |
+
pd.DataFrame(rouge_dict, index = ['pegasus'])
|
| 110 |
+
|
| 111 |
+
dialogue_token_len = len([tokenizer.encode(s) for s in dataset_samsum['train']['dialogue']])
|
| 112 |
+
|
| 113 |
+
summary_token_len = len([tokenizer.encode(s) for s in dataset_samsum['train']['summary']])
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
|
| 117 |
+
axes[0].hist(dialogue_token_len, bins = 20, color = 'C0', edgecolor = 'C0' )
|
| 118 |
+
axes[0].set_title("Dialogue Token Length")
|
| 119 |
+
axes[0].set_xlabel("Length")
|
| 120 |
+
axes[0].set_ylabel("Count")
|
| 121 |
+
|
| 122 |
+
axes[1].hist(summary_token_len, bins = 20, color = 'C0', edgecolor = 'C0' )
|
| 123 |
+
axes[1].set_title("Summary Token Length")
|
| 124 |
+
axes[1].set_xlabel("Length")
|
| 125 |
+
plt.tight_layout()
|
| 126 |
+
plt.show()
|
| 127 |
+
|
| 128 |
+
def convert_examples_to_features(example_batch):
|
| 129 |
+
input_encodings = tokenizer(example_batch['dialogue'] , max_length = 1024, truncation = True )
|
| 130 |
+
|
| 131 |
+
with tokenizer.as_target_tokenizer():
|
| 132 |
+
target_encodings = tokenizer(example_batch['summary'], max_length = 128, truncation = True )
|
| 133 |
+
|
| 134 |
+
return {
|
| 135 |
+
'input_ids' : input_encodings['input_ids'],
|
| 136 |
+
'attention_mask': input_encodings['attention_mask'],
|
| 137 |
+
'labels': target_encodings['input_ids']
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
dataset_samsum_pt = dataset_samsum.map(convert_examples_to_features, batched = True)
|
| 141 |
+
|
| 142 |
+
from transformers import DataCollatorForSeq2Seq
|
| 143 |
+
|
| 144 |
+
seq2seq_data_collator = DataCollatorForSeq2Seq(tokenizer, model=model_pegasus)
|
| 145 |
+
|
| 146 |
+
from google.colab import drive
|
| 147 |
+
drive.mount('/content/drive')
|
| 148 |
+
|
| 149 |
+
from transformers import TrainingArguments, Trainer
|
| 150 |
+
|
| 151 |
+
trainer_args = TrainingArguments(
|
| 152 |
+
output_dir='summary-bart', num_train_epochs=1, warmup_steps=500,
|
| 153 |
+
per_device_train_batch_size=1, per_device_eval_batch_size=1,
|
| 154 |
+
weight_decay=0.01, logging_steps=10,
|
| 155 |
+
evaluation_strategy='steps', eval_steps=500, save_steps=1e6,
|
| 156 |
+
gradient_accumulation_steps=16
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
trainer = Trainer(model=model_pegasus, args=trainer_args,
|
| 160 |
+
tokenizer=tokenizer, data_collator=seq2seq_data_collator,
|
| 161 |
+
train_dataset=dataset_samsum_pt["train"],
|
| 162 |
+
eval_dataset=dataset_samsum_pt["validation"])
|
| 163 |
+
|
| 164 |
+
trainer.train()
|
| 165 |
+
|
| 166 |
+
score = calculate_metric_on_test_ds(
|
| 167 |
+
dataset_samsum['test'], rouge_metric, trainer.model, tokenizer, batch_size = 2, column_text = 'dialogue', column_summary= 'summary'
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
rouge_dict = dict((rn, score[rn].mid.fmeasure ) for rn in rouge_names )
|
| 171 |
+
|
| 172 |
+
pd.DataFrame(rouge_dict, index = [f'pegasus'] )
|
| 173 |
+
|
| 174 |
+
model_pegasus.save_pretrained("bart-samsum-model")
|
| 175 |
+
|
| 176 |
+
tokenizer.save_pretrained("tokenizer")
|
| 177 |
+
|
| 178 |
+
dataset_samsum = load_dataset("samsum")
|
| 179 |
+
|
| 180 |
+
tokenizer = AutoTokenizer.from_pretrained("tokenizer")
|
| 181 |
+
|
| 182 |
+
sample_text = dataset_samsum["test"][0]["dialogue"]
|
| 183 |
+
|
| 184 |
+
reference = dataset_samsum["test"][0]["summary"]
|
| 185 |
+
|
| 186 |
+
gen_kwargs = {"length_penalty": 0.8, "num_beams":8, "max_length": 128}
|
| 187 |
+
|
| 188 |
+
pipe = pipeline("summarization", model="bart-samsum-model",tokenizer=tokenizer)
|
| 189 |
+
|
| 190 |
+
print("Dialogue:")
|
| 191 |
+
print(sample_text)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
print("\nReference Summary:")
|
| 195 |
+
print(reference)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
print("\nModel Summary:")
|
| 199 |
+
print(pipe(sample_text, **gen_kwargs)[0]["summary_text"])
|