philschmid blog

Financial Text Summarization with Hugging Face Transformers, Keras & Amazon SageMaker

#HuggingFace #Keras #SageMaker #Tensorflow
, January 19, 2022 · 11 min read

Photo by Visual Stories || Micheile on Unsplash

Welcome to this end-to-end Financial Summarization (NLP) example using Keras and Hugging Face Transformers. In this demo, we will use the Hugging Faces transformers and datasets library together with Tensorflow & Keras to fine-tune a pre-trained seq2seq transformer for financial summarization.

We are going to use the Trade the Event dataset for abstractive text summarization. The benchmark dataset contains 303893 news articles range from 2020/03/01 to 2021/05/06. The articles are downloaded from the PRNewswire and Businesswire.

More information for the dataset can be found at the repository.

We are going to use all of the great Feature from the Hugging Face ecosystem like model versioning and experiment tracking as well as all the great features of Keras like Early Stopping and Tensorboard.

You can find the notebook and scripts in this repository: philschmid/keras-financial-summarization-huggingfacePublic.


1 !pip install git+ --upgrade
1 #!pip install "tensorflow==2.6.0"
2 !pip install transformers "datasets>=1.17.0" tensorboard rouge_score nltk --upgrade
3 # install gdown for downloading the dataset
4 !pip install gdown

install git-lfs to push models to

1 !sudo apt-get install git-lfs

This example will use the Hugging Face Hub as a remote model versioning service. To be able to push our model to the Hub, you need to register on the Hugging Face. If you already have an account you can skip this step. After you have an account, we will use the notebook_login util from the huggingface_hub package to log into our account and store our token (access key) on the disk.

1 from huggingface_hub import notebook_login
3 notebook_login()

Setup & Configuration

In this step, we will define global configurations and parameters, which are used across the whole end-to-end fine-tuning process, e.g. tokenizer and model we will use.

In this example are we going to fine-tune the sshleifer/distilbart-cnn-12-6 a distilled version of the BART transformer. Since the original repository didn’t include Keras weights I converted the model to Keras using from_pt=True, when loading the model.

1 model_id = "philschmid/tf-distilbart-cnn-12-6"

You can easily adjust the model_id to another Vision Transformer model, e.g. google/pegasus-xsum

Dataset & Pre-processing

We are going to use the Trade the Event dataset for abstractive text summarization. The benchmark dataset contains 303893 news articles range from 2020/03/01 to 2021/05/06. The articles are downloaded from the PRNewswire and Businesswire.

The we will use the column text as INPUT and title as summarization TARGET.


1 {"text": "PLANO, Texas, Dec. 8, 2020 /PRNewswire/ --European Wax Center(EWC), the leading personal care franchise brand that offers expert wax services from certified specialists is proud to welcome a new Chief Financial Officer, Jennifer Vanderveldt. In the midst of European Wax Center\"s accelerated growth plan, Jennifer will lead the Accounting and FP&A teams to continue to widen growth and organizational initiatives. (PRNewsfoto/European Wax Center) ...",
2 "title": "European Wax Center Welcomes Jennifer Vanderveldt As Chief Financial Officer",
3 "pub_time": "2020-12-08 09:00:00-05:00",
4 "labels": {"ticker": "MIK",
5 "start_time": "2020-12-08 09:00:00-05:00",
6 "start_price_open": 12.07,
7 "start_price_close": 12.07,
8 "end_price_1day": 12.8,
9 "end_price_2day": 12.4899,
10 "end_price_3day": 13.0,
11 "end_time_1day": "2020-12-08 19:11:00-05:00",
12 "end_time_2day": "2020-12-09 18:45:00-05:00",
13 "end_time_3day": "2020-12-10 19:35:00-05:00",
14 "highest_price_1day": 13.2,
15 "highest_price_2day": 13.2,
16 "highest_price_3day": 13.2,
17 "highest_time_1day": "2020-12-08 10:12:00-05:00",
18 "highest_time_2day": "2020-12-08 10:12:00-05:00",
19 "highest_time_3day": "2020-12-08 10:12:00-05:00",
20 "lowest_price_1day": 11.98,
21 "lowest_price_2day": 11.98,
22 "lowest_price_3day": 11.98,
23 "lowest_time_1day": "2020-12-08 09:13:00-05:00",
24 "lowest_time_2day": "2020-12-08 09:13:00-05:00",
25 "lowest_time_3day": "2020-12-08 09:13:00-05:00"}}

The TradeTheEvent is not yet available as a dataset in the datasets library. To be able to create a Dataset instance we need to write a small little helper function, which converts the downloaded .json to a jsonl file to then be then loaded with load_dataset.

As a first step, we need to download the dataset to our filesystem using gdown.

1 !gdown ""

We should now have a file called evluate_news.jsonl in our filesystem and can write a small helper function to convert the .json to a jsonl file.

1 src_path="evaluate_news.json"
2 target_path='tde_dataset.jsonl'
4 import json
5 with open(src_path,"r+") as f, open(target_path, 'w') as outfile:
6 JSON_file = json.load(f)
7 for entry in JSON_file:
8 json.dump(entry, outfile)
9 outfile.write('\n')

We can now remove the evaluate_news.json to save some space and avoid confusion.

1 !rm -rf evaluate_news.json

To load our dataset we can use the load_dataset function from the datasets library.

1 from datasets import load_dataset
3 target_path='tde_dataset.jsonl'
5 ds = load_dataset('json', data_files=target_path)

Pre-processing & Tokenization

To train our model we need to convert our “Natural Language” to token IDs. This is done by a 🤗 Transformers Tokenizer which will tokenize the inputs (including converting the tokens to their corresponding IDs in the pretrained vocabulary). If you are not sure what this means check out chapter 6 of the Hugging Face Course.

before we tokenize our dataset we remove all of the unused columns for the summarization task to save some time and storage.

1 to_remove_columns = ["pub_time","labels"]
3 ds = ds["train"].remove_columns(to_remove_columns)
1 from transformers import AutoTokenizer
3 tokenizer = AutoTokenizer.from_pretrained(model_id)

Compared to a text-classification in summarization our labels are also text. This means we need to apply truncation to both the text and title title to ensure we don’t pass excessively long inputs to our model. The tokenizers in 🤗 Transformers provide a nifty as_target_tokenizer() function that allows you to tokenize the labels in parallel to the inputs.

In addition to this we define values for max_input_length (maximum lenght before the text is trubcated) and max_target_length (maximum lenght for the summary/prediction).

1 max_input_length = 512
2 max_target_length = 64
5 def preprocess_function(examples):
6 model_inputs = tokenizer(
7 examples["text"], max_length=max_input_length, truncation=True
8 )
9 # Set up the tokenizer for targets
10 with tokenizer.as_target_tokenizer():
11 labels = tokenizer(
12 examples["title"], max_length=max_target_length, truncation=True
13 )
15 model_inputs["labels"] = labels["input_ids"]
16 return model_inputs
18 tokenized_datasets =, batched=True)

Since our dataset doesn’t includes any split we need to train_test_split ourself to have an evaluation/test dataset for evaluating the result during and after training.

1 # test size will be 15% of train dataset
2 test_size=.15
4 processed_dataset = tokenized_datasets.shuffle().train_test_split(test_size=test_size)

Fine-tuning the model using Keras

Now that our dataset is processed, we can download the pretrained model and fine-tune it. But before we can do this we need to convert our Hugging Face datasets Dataset into a For this, we will use the .to_tf_dataset method and a data collator (Data collators are objects that will form a batch by using a list of dataset elements as input).


1 from huggingface_hub import HfFolder
2 import tensorflow as tf
5 num_train_epochs = 5
6 train_batch_size = 8
7 eval_batch_size = 8
8 learning_rate = 5.6e-5
9 weight_decay_rate=0.01
10 num_warmup_steps=0
11 output_dir=model_id.split("/")[1]
12 hub_token = HfFolder.get_token() # or your token directly "hf_xxx"
13 hub_model_id = f'{model_id.split("/")[1]}-tradetheevent'
14 fp16=True
16 # Train in mixed-precision float16
17 # Comment this line out if you're using a GPU that will not benefit from this
18 if fp16:
19 tf.keras.mixed_precision.set_global_policy("mixed_float16")

Converting the dataset to a

to create our we need to download the model to be able to initialize our data collator.

1 from transformers import TFAutoModelForSeq2SeqLM
2 # load pre-trained model
3 model = TFAutoModelForSeq2SeqLM.from_pretrained(model_id)

to convert our dataset we use the .to_tf_dataset method.

1 from transformers import DataCollatorForSeq2Seq
3 # Data collator that will dynamically pad the inputs received, as well as the labels.
4 data_collator = DataCollatorForSeq2Seq(tokenizer, model=model, return_tensors="tf")
6 # converting our train dataset to
7 tf_train_dataset = processed_dataset["train"].to_tf_dataset(
8 columns=["input_ids", "attention_mask", "labels"],
9 shuffle=True,
10 batch_size=train_batch_size,
11 collate_fn=data_collator)
13 # converting our test dataset to
14 tf_eval_dataset = processed_dataset["test"].to_tf_dataset(
15 columns=["input_ids", "attention_mask", "labels"],
16 shuffle=True,
17 batch_size=eval_batch_size,
18 collate_fn=data_collator)

Create optimizer and compile the model

1 from transformers import create_optimizer
2 import tensorflow as tf
5 # create optimizer wight weigh decay
6 num_train_steps = len(tf_train_dataset) * num_train_epochs
7 optimizer, lr_schedule = create_optimizer(
8 init_lr=learning_rate,
9 num_train_steps=num_train_steps,
10 weight_decay_rate=weight_decay_rate,
11 num_warmup_steps=num_warmup_steps,
12 )
14 # compile model
15 model.compile(optimizer=optimizer)


As mentioned in the beginning we want to use the Hugging Face Hub for model versioning and monitoring. Therefore we want to push our model weights, during training and after training to the Hub to version it. Additionally, we want to track the performance during training therefore we will push the Tensorboard logs along with the weights to the Hub to use the “Training Metrics” Feature to monitor our training in real-time.

1 import os
2 from transformers.keras_callbacks import PushToHubCallback
3 from tensorflow.keras.callbacks import TensorBoard as TensorboardCallback
5 callbacks=[]
7 callbacks.append(TensorboardCallback(log_dir=os.path.join(output_dir,"logs")))
8 if hub_token:
9 callbacks.append(PushToHubCallback(output_dir=output_dir,
10 tokenizer=tokenizer,
11 hub_model_id=hub_model_id,
12 hub_token=hub_token))


You can find the the Tensorboard on the Hugging Face Hub at your model repository at Training Metrics. We can clearly see that the experiment I ran is not perfect since the validation loss increases again after time. But this is a good example of how to use the Tensorboard callback and the Hugging Face Hub. As a next step i would probably switch to Amazon SageMaker and run multiple experiments with the Tensorboard integration and EarlyStopping to find the best hyperparameters.


Start training with calling

1 train_results =
2 tf_train_dataset,
3 validation_data=tf_eval_dataset,
4 callbacks=callbacks,
5 epochs=num_train_epochs,
6 )


The most commonly used metrics to evaluate summarization task is rogue_score short for Recall-Oriented Understudy for Gisting Evaluation). This metric does not behave like the standard accuracy: it will compare a generated summary against a set of reference summaries

1 from datasets import load_metric
2 from tqdm import tqdm
3 import numpy as np
4 import nltk
6 from nltk.tokenize import sent_tokenize
9 metric = load_metric("rouge")
12 def evaluate(model, dataset):
13 all_predictions = []
14 all_labels = []
15 for batch in tqdm(dataset):
16 predictions = model.generate(batch["input_ids"])
17 decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)
18 labels = batch["labels"].numpy()
19 labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
20 decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
21 decoded_preds = ["\n".join(sent_tokenize(pred.strip())) for pred in decoded_preds]
22 decoded_labels = ["\n".join(sent_tokenize(label.strip())) for label in decoded_labels]
23 all_predictions.extend(decoded_preds)
24 all_labels.extend(decoded_labels)
25 result = metric.compute(
26 predictions=decoded_preds, references=decoded_labels, use_stemmer=True
27 )
28 result = {key: value.mid.fmeasure * 100 for key, value in result.items()}
29 return {k: round(v, 4) for k, v in result.items()}
31 results = evaluate(model, tf_eval_dataset)

Run Managed Training using Amazon Sagemaker

If you want to run this examples on Amazon SageMaker to benefit from the Training Platform follow the cells below. I converted the Notebook into a python script, which accepts same hyperparameter and can we run on SageMaker using the HuggingFace estimator.

install SageMaker and gdown.

1 #!pip install sagemaker gdown

Download the dataset and convert it to jsonlines.

1 !gdown ""
3 src_path="evaluate_news.json"
4 target_path='tde_dataset.jsonl'
6 import json
7 with open(src_path,"r+") as f, open(target_path, 'w') as outfile:
8 JSON_file = json.load(f)
9 for entry in JSON_file:
10 json.dump(entry, outfile)
11 outfile.write('\n')

As next step we create a SageMaker session to start our training. The snippet below works in Amazon SageMaker Notebook Instances or Studio. If you are running in a local environment check-out the documentation for how to initialize your session.

1 import sagemaker
3 sess = sagemaker.Session()
4 # sagemaker session bucket -> used for uploading data, models and logs
5 # sagemaker will automatically create this bucket if it not exists
6 sagemaker_session_bucket=None
7 if sagemaker_session_bucket is None and sess is not None:
8 # set to default bucket if a bucket name is not given
9 sagemaker_session_bucket = sess.default_bucket()
11 role = sagemaker.get_execution_role()
12 sess = sagemaker.Session(default_bucket=sagemaker_session_bucket)
14 print(f"sagemaker role arn: {role}")
15 print(f"sagemaker bucket: {sess.default_bucket()}")
16 print(f"sagemaker session region: {sess.boto_region_name}")

Now, we can define our HuggingFace estimator and Hyperparameter.

1 from sagemaker.huggingface import HuggingFace
3 # gets role for executing training job
4 role = sagemaker.get_execution_role()
5 hyperparameters = {
6 'model_id': 'philschmid/tf-distilbart-cnn-12-6',
7 'dataset_file_name': 'tde_dataset.jsonl',
8 'num_train_epochs': 5,
9 'train_batch_size': 8,
10 'eval_batch_size': 8,
11 'learning_rate': 5e-5,
12 'weight_decay_rate': 0.01,
13 'num_warmup_steps': 0,
14 'hub_token': HfFolder.get_token(),
15 'hub_model_id': 'sagemaker-tf-distilbart-cnn-12-6',
16 'fp16': True
17 }
20 # creates Hugging Face estimator
21 huggingface_estimator = HuggingFace(
22 entry_point='',
23 source_dir='./scripts',
24 instance_type='ml.p3.2xlarge',
25 instance_count=1,
26 role=role,
27 transformers_version='4.12.3',
28 tensorflow_version='2.5.1',
29 py_version='py36',
30 hyperparameters = hyperparameters
31 )

Opload our raw dataset to s3

1 from sagemaker.s3 import S3Uploader
4 dataset_uri = S3Uploader.upload(local_path="tde_dataset.jsonl",desired_s3_uri=f"s3://{sess.default_bucket()}/TradeTheEvent/tde_dataset.jsonl")

After the dataset is uploaded we can start the training a pass our s3_uri as argument.

1 # starting the train job
2{"dataset": dataset_uri})


We managed to successfully fine-tune a Seq2Seq BART Transformer using Transformers and Keras, without any heavy lifting or complex and unnecessary boilerplate code. The new utilities like .to_tf_dataset are improving the developer experience of the Hugging Face ecosystem to become more Keras and TensorFlow friendly. Combining those new features with the Hugging Face Hub we get a fully-managed MLOps pipeline for model-versioning and experiment management using Keras callback API. Through SageMaker we could easily scale our Training. This was especially helpful since the training takes 10-12h depending on how many epochs we ran.

You can find the code here and feel free to open a thread on the forum.

Thanks for reading. If you have any questions, feel free to contact me, through Github, or on the forum. You can also connect with me on Twitter or LinkedIn.