Path: blob/master/examples/nlp/abstractive_summarization_with_bart.py
3507 views
"""1Title: Abstractive Text Summarization with BART2Author: [Abheesht Sharma](https://github.com/abheesht17/)3Date created: 2023/07/084Last modified: 2024/03/205Description: Use KerasHub to fine-tune BART on the abstractive summarization task.6Accelerator: GPU7Converted to Keras 3 by: [Sitam Meur](https://github.com/sitamgithub-MSIT)8"""910"""11## Introduction1213In the era of information overload, it has become crucial to extract the crux14of a long document or a conversation and express it in a few sentences. Owing15to the fact that summarization has widespread applications in different domains,16it has become a key, well-studied NLP task in recent years.1718[Bidirectional Autoregressive Transformer (BART)](https://arxiv.org/abs/1910.13461)19is a Transformer-based encoder-decoder model, often used for20sequence-to-sequence tasks like summarization and neural machine translation.21BART is pre-trained in a self-supervised fashion on a large text corpus. During22pre-training, the text is corrupted and BART is trained to reconstruct the23original text (hence called a "denoising autoencoder"). Some pre-training tasks24include token masking, token deletion, sentence permutation (shuffle sentences25and train BART to fix the order), etc.2627In this example, we will demonstrate how to fine-tune BART on the abstractive28summarization task (on conversations!) using KerasHub, and generate summaries29using the fine-tuned model.30"""3132"""33## Setup3435Before we start implementing the pipeline, let's install and import all the36libraries we need. We'll be using the KerasHub library. We will also need a37couple of utility libraries.38"""3940"""shell41pip install git+https://github.com/keras-team/keras-hub.git py7zr -q42"""4344"""45This examples uses [Keras 3](https://keras.io/keras_3/) to work in any of46`"tensorflow"`, `"jax"` or `"torch"`. Support for Keras 3 is baked into47KerasHub, simply change the `"KERAS_BACKEND"` environment variable to select48the backend of your choice. We select the JAX backend below.49"""5051import os5253os.environ["KERAS_BACKEND"] = "jax"5455"""56Import all necessary libraries.57"""5859import py7zr60import time6162import keras_hub63import keras64import tensorflow as tf65import tensorflow_datasets as tfds6667"""68Let's also define our hyperparameters.69"""7071BATCH_SIZE = 872NUM_BATCHES = 60073EPOCHS = 1 # Can be set to a higher value for better results74MAX_ENCODER_SEQUENCE_LENGTH = 51275MAX_DECODER_SEQUENCE_LENGTH = 12876MAX_GENERATION_LENGTH = 407778"""79## Dataset8081Let's load the [SAMSum dataset](https://arxiv.org/abs/1911.12237). This dataset82contains around 15,000 pairs of conversations/dialogues and summaries.83"""8485# Download the dataset.86filename = keras.utils.get_file(87"corpus.7z",88origin="https://huggingface.co/datasets/samsum/resolve/main/data/corpus.7z",89)9091# Extract the `.7z` file.92with py7zr.SevenZipFile(filename, mode="r") as z:93z.extractall(path="/root/tensorflow_datasets/downloads/manual")9495# Load data using TFDS.96samsum_ds = tfds.load("samsum", split="train", as_supervised=True)9798"""99The dataset has two fields: `dialogue` and `summary`. Let's see a sample.100"""101for dialogue, summary in samsum_ds:102print(dialogue.numpy())103print(summary.numpy())104break105106"""107We'll now batch the dataset and retain only a subset of the dataset for the108purpose of this example. The dialogue is fed to the encoder, and the109corresponding summary serves as input to the decoder. We will, therefore, change110the format of the dataset to a dictionary having two keys: `"encoder_text"` and111`"decoder_text"`.This is how `keras_hub.models.BartSeq2SeqLMPreprocessor`112expects the input format to be.113"""114115train_ds = (116samsum_ds.map(117lambda dialogue, summary: {"encoder_text": dialogue, "decoder_text": summary}118)119.batch(BATCH_SIZE)120.cache()121)122train_ds = train_ds.take(NUM_BATCHES)123124"""125## Fine-tune BART126127Let's load the model and preprocessor first. We use sequence lengths of 512128and 128 for the encoder and decoder, respectively, instead of 1024 (which is the129default sequence length). This will allow us to run this example quickly130on Colab.131132If you observe carefully, the preprocessor is attached to the model. What this133means is that we don't have to worry about preprocessing the text inputs;134everything will be done internally. The preprocessor tokenizes the encoder text135and the decoder text, adds special tokens and pads them. To generate labels136for auto-regressive training, the preprocessor shifts the decoder text one137position to the right. This is done because at every timestep, the model is138trained to predict the next token.139"""140141preprocessor = keras_hub.models.BartSeq2SeqLMPreprocessor.from_preset(142"bart_base_en",143encoder_sequence_length=MAX_ENCODER_SEQUENCE_LENGTH,144decoder_sequence_length=MAX_DECODER_SEQUENCE_LENGTH,145)146bart_lm = keras_hub.models.BartSeq2SeqLM.from_preset(147"bart_base_en", preprocessor=preprocessor148)149150bart_lm.summary()151152"""153Define the optimizer and loss. We use the Adam optimizer with a linearly154decaying learning rate. Compile the model.155"""156157optimizer = keras.optimizers.AdamW(158learning_rate=5e-5,159weight_decay=0.01,160epsilon=1e-6,161global_clipnorm=1.0, # Gradient clipping.162)163# Exclude layernorm and bias terms from weight decay.164optimizer.exclude_from_weight_decay(var_names=["bias"])165optimizer.exclude_from_weight_decay(var_names=["gamma"])166optimizer.exclude_from_weight_decay(var_names=["beta"])167168loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True)169170bart_lm.compile(171optimizer=optimizer,172loss=loss,173weighted_metrics=["accuracy"],174)175176"""177Let's train the model!178"""179180bart_lm.fit(train_ds, epochs=EPOCHS)181182"""183## Generate summaries and evaluate them!184185Now that the model has been trained, let's get to the fun part - actually186generating summaries! Let's pick the first 100 samples from the validation set187and generate summaries for them. We will use the default decoding strategy, i.e.,188greedy search.189190Generation in KerasHub is highly optimized. It is backed by the power of XLA.191Secondly, key/value tensors in the self-attention layer and cross-attention layer192in the decoder are cached to avoid recomputation at every timestep.193"""194195196def generate_text(model, input_text, max_length=200, print_time_taken=False):197start = time.time()198output = model.generate(input_text, max_length=max_length)199end = time.time()200print(f"Total Time Elapsed: {end - start:.2f}s")201return output202203204# Load the dataset.205val_ds = tfds.load("samsum", split="validation", as_supervised=True)206val_ds = val_ds.take(100)207208dialogues = []209ground_truth_summaries = []210for dialogue, summary in val_ds:211dialogues.append(dialogue.numpy())212ground_truth_summaries.append(summary.numpy())213214# Let's make a dummy call - the first call to XLA generally takes a bit longer.215_ = generate_text(bart_lm, "sample text", max_length=MAX_GENERATION_LENGTH)216217# Generate summaries.218generated_summaries = generate_text(219bart_lm,220val_ds.map(lambda dialogue, _: dialogue).batch(8),221max_length=MAX_GENERATION_LENGTH,222print_time_taken=True,223)224225"""226Let's see some of the summaries.227"""228for dialogue, generated_summary, ground_truth_summary in zip(229dialogues[:5], generated_summaries[:5], ground_truth_summaries[:5]230):231print("Dialogue:", dialogue)232print("Generated Summary:", generated_summary)233print("Ground Truth Summary:", ground_truth_summary)234print("=============================")235236"""237The generated summaries look awesome! Not bad for a model trained only for 1238epoch and on 5000 examples :)239"""240241242