Notebooks
A
Amazon Web Services
Amazon JumpStart Sentence Pair Classification

Amazon JumpStart Sentence Pair Classification

data-scienceinferencearchivedamazon-sagemaker-examplesreinforcement-learningmachine-learningawsexamplesdeep-learningsagemakerjupyter-notebooktrainingmlops

Introduction to JumpStart - Sentence Pair Classification


This notebook's CI test result for us-west-2 is as follows. CI test results in other regions can be found at the end of the notebook.

This us-west-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable



Welcome to Amazon SageMaker JumpStart! You can use JumpStart to solve many Machine Learning tasks through one-click in SageMaker Studio, or through SageMaker JumpStart API.

In this demo notebook, we demonstrate how to use the JumpStart API for Sentence Pair Classification. Sentence Pair Classification refers to classifying a pair of input sentence to one of the class labels of the training dataset. We demonstrate two use cases of Sentence Pair Classification models:

  • How to use a Transformer model pre-trained on English dataset, and fine-tuned on QNLI dataset, to perform Natural Language Inference.
  • How to fine-tune a pre-trained Transformer model to a custom dataset, and then run inference on the fine-tuned model.

Note: This notebook was tested on ml.t3.medium instance in Amazon SageMaker Studio with Python 3 (Data Science) kernel and in Amazon SageMaker Notebook instance with conda_python3 kernel.


1. Set Up


Before executing the notebook, there are some initial steps required for setup. This notebook requires latest version of sagemaker and ipywidgets.


[ ]

To train and host on Amazon SageMaker, we need to setup and authenticate the use of AWS services. Here, we use the execution role associated with the current notebook instance as the AWS account role with SageMaker access. It has necessary permissions, including access to your data in S3.


[ ]

2. Select a pre-trained model


You can continue with the default model, or can choose a different model from the dropdown generated upon running the next cell. A complete list of JumpStart models can also be accessed at JumpStart Models.


[ ]

[Optional] Select a different JumpStart model. Here, we download jumpstart model_manifest file from the jumpstart s3 bucket, filter-out all the Sentence Pair Classification models and select a model.


[ ]

3. Run inference on the pre-trained model


Using JumpStart, we can perform inference on the pre-trained model, even without fine-tuning it first on a custom dataset. For this example, that means on a pair of input sentences predicting the class label from one of the 2 classes of the QNLI dataset: entail, no-entail.


3.1. Retrieve JumpStart Artifacts & Deploy an Endpoint


We retrieve the deploy_image_uri, deploy_source_uri, and base_model_uri for the pre-trained model. To host the pre-trained model, we create an instance of sagemaker.model.Model and deploy it.


[ ]

3.2. Example input sentences for inference


Let's put in some example sentence pairs. You can put in any pairs of sentences, the model will predict whether the second sentence entails the first sentence or not. These examples are taken from QNLI dataset downloaded from TensorFlow. Apache 2.0 License. Dataset Homepage. CC BY-SA 4.0 License.


[ ]

3.3. Query endpoint and parse response


Input to the endpoint is a pair of sentences. Response from the endpoint is a dictionary containing the predicted class label, and a list of class label probabilities.


[ ]

3.4. Clean up the endpoint

[ ]

4. Finetune the pre-trained model on a custom dataset


Previously, we saw how to run inference on a pre-trained model, which was fine-tuned on QNLI dataset. Next, we discuss how a model can be finetuned to a custom dataset.

The Text Embedding model can be fine-tuned on any sentence pair classification dataset in the same way the model available for inference has been fine-tuned on the QNLI dataset. The model available for fine-tuning attaches a binary classification layer to the Text Embedding model and initializes the layer parameters to random values. The fine-tuning step fine-tunes all the model parameters to minimize prediction error on the input data and returns the fine-tuned model. The model returned by fine-tuning can be further deployed for inference. Below are the instructions for how the training data should be formatted for input to the model.

  • Input: A directory containing a 'data.csv' file.
    • Each row of the first column of 'data.csv' should have 0/1 integer class labels.
    • Each row of the second column should have the corresponding first sentence.
    • Each row of the third column should have the corresponding second sentence.
  • Output: A trained model that can be deployed for inference.

Below is an example of 'data.csv' file showing values in its first three columns. Note that the file should not have any header.

0What is the Grotto at Notre Dame?Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection.
1What is the Grotto at Notre Dame?It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858.
0What sits on top of the Main Building at Notre Dame?Atop the Main Building's gold dome is a golden statue of the Virgin Mary.
.........

QNLI dataset is downloaded from TensorFlow. Apache 2.0 License. Dataset Homepage. CC BY-SA 4.0 License.


4.1. Retrieve JumpStart Training artifacts


Here, for the selected model, we retrieve the training docker container, the training algorithm source, the pre-trained model, and a python dictionary of the training hyper-parameters that the algorithm accepts with their default values. Note that the model_version="*" fetches the latest model. Also, we do need to specify the training_instance_type to fetch train_image_uri.


[ ]

4.2. Set Training parameters


Now that we are done with all the setup that is needed, we are ready to fine-tune our Sentence Pair Classification model. To begin, let us create a sagemaker.estimator.Estimator object. This estimator will launch the training job.

There are two kinds of parameters that need to be set for training.

The first one are the parameters for the training job. These include: (i) Training data path. This is S3 folder in which the input data is stored, (ii) Output path: This the s3 folder in which the training output is stored. (iii) Training instance type: This indicates the type of machine on which to run the training. Typically, we use GPU instances for these training. We defined the training instance type above to fetch the correct train_image_uri.

The second set of parameters are algorithm specific training hyper-parameters.


[ ]

For algorithm specific hyper-parameters, we start by fetching python dictionary of the training hyper-parameters that the algorithm accepts with their default values. This can then be overridden to custom values.


[ ]

4.3. Train with Automatic Model Tuning (HPO)


Amazon SageMaker automatic model tuning, also known as hyperparameter tuning, finds the best version of a model by running many training jobs on your dataset using the algorithm and ranges of hyperparameters that you specify. It then chooses the hyperparameter values that result in a model that performs the best, as measured by a metric that you choose. We will use a HyperparameterTuner object to interact with Amazon SageMaker hyperparameter tuning APIs.


[ ]

4.4. Start Training


We start by creating the estimator object with all the required assets and then launch the training job.


[ ]

4.5. Deploy & run Inference on the fine-tuned model


A trained model does nothing on its own. We now want to use the model to perform inference. For this example, that means predicting the class label of an input sentence. We follow the same steps as in 3. Run inference on the pre-trained model. We start by retrieving the jumpstart artifacts for deploying an endpoint. However, instead of base_predictor, we deploy the spc_estimator that we fine-tuned.


[ ]

Let's put in some example sentence pairs. You can put in any pairs of sentences, the model will predict whether the second sentence entails the first sentence or not. These examples are taken from QNLI dataset downloaded from TensorFlow. Apache 2.0 License. Dataset Homepage. CC BY-SA 4.0 License.

[ ]

Next, we query the finetuned model, parse the response and print the predictions.


[ ]

Next, we clean up the deployed endpoint.


[ ]

Notebook CI Test Results

This notebook was tested in multiple regions. The test results are as follows, except for us-west-2 which is shown at the top of the notebook.

This us-east-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This us-east-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This us-west-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This ca-central-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This sa-east-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This eu-west-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This eu-west-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This eu-west-3 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This eu-central-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This eu-north-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This ap-southeast-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This ap-southeast-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This ap-northeast-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This ap-northeast-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This ap-south-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable