SageMaker JumpStart Foundation Models - Fine-tuning text generation GPT-J 6B model on domain specific dataset


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


  1. Set Up

  2. Select Text Generation Model GTP-J 6B

  3. Run Inference on the Pre-trained Model without finetuning

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

1. Set Up

Before executing the notebook, there are some initial steps required for setup.

[ ]:
!pip install ipywidgets==7.0.0 --quiet
!pip install --upgrade sagemaker --quiet

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.

[ ]:
import sagemaker, boto3, json
from sagemaker.session import Session

sagemaker_session = Session()
aws_role = sagemaker_session.get_caller_identity_arn()
aws_region = boto3.Session().region_name
sess = sagemaker.Session()

2. Select Text Generation Model GTP-J 6B

[ ]:
model_id, model_version = "huggingface-textgeneration1-gpt-j-6b", "1.*"

3. Run Inference on the Pre-trained Model without finetuning

Using SageMaker, we can directly perform inference on the pre-trained GPT-J 6B model. GPT-J 6B is an open source 6 billion parameter model released by Eleuther AI. GPT-J 6B has been trained on a large corpus of text data (the Pile dataset) and is capable of performing various natural language processing tasks such as text generation, text classification, and text summarization.

3.1. Retrieve 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 <https://sagemaker.readthedocs.io/en/stable/api/inference/model.html>`__ and deploy it.

[ ]:
from sagemaker import image_uris, model_uris, script_uris
from sagemaker.model import Model
from sagemaker.predictor import Predictor
from sagemaker.utils import name_from_base

endpoint_name = name_from_base(f"jumpstart-example-{model_id}")

inference_instance_type = "ml.g5.12xlarge"

# Retrieve the inference docker container uri.
deploy_image_uri = image_uris.retrieve(
    region=None,
    framework=None,
    image_scope="inference",
    model_id=model_id,
    model_version=model_version,
    instance_type=inference_instance_type,
)

# Retrieve the model uri.
model_uri = model_uris.retrieve(
    model_id=model_id, model_version=model_version, model_scope="inference"
)

# Create the SageMaker model instance. Note that we need to pass Predictor class when we deploy model through Model class,
# for being able to run inference through the sagemaker API.
model = Model(
    image_uri=deploy_image_uri,
    model_data=model_uri,
    role=aws_role,
    predictor_cls=Predictor,
    name=endpoint_name,
)

# deploy the Model. TODO
base_model_predictor = model.deploy(
    initial_instance_count=1,
    instance_type=inference_instance_type,
    endpoint_name=endpoint_name,
)

3.2. Query endpoint and parse response

The model takes a text string as input and predicts next words in the sequence. We use three of following input examples.

  1. This Form 10-K report shows that

  2. We serve consumers through

  3. Our vision is

The input examples are related to company’s perforamnce in financial report. You will see the outputs from the model without finetuning are limited in providing insightful contents.

[ ]:
import json
import boto3


def query_endpoint_with_json_payload(encoded_json, endpoint_name):
    client = boto3.client("runtime.sagemaker")
    response = client.invoke_endpoint(
        EndpointName=endpoint_name, ContentType="application/json", Body=encoded_json
    )
    return response


def parse_response_multiple_texts(query_response):
    generated_text = []
    model_predictions = json.loads(query_response["Body"].read())
    return model_predictions[0]
[ ]:
parameters = {
    "max_length": 400,
    "num_return_sequences": 1,
    "top_k": 250,
    "top_p": 0.8,
    "do_sample": True,
    "temperature": 1,
}

res_gpt_before_finetune = []
for quota_text in [
    "This Form 10-K report shows that",
    "We serve consumers through",
    "Our vision is",
]:
    payload = {"text_inputs": f"{quota_text}:", **parameters}

    query_response = query_endpoint_with_json_payload(
        json.dumps(payload).encode("utf-8"), endpoint_name=endpoint_name
    )
    generated_texts = parse_response_multiple_texts(query_response)[0]["generated_text"]
    res_gpt_before_finetune.append(generated_texts)
    print(generated_texts)
    print("\n")

3.3. Clean up the endpoint

[ ]:
# Delete the SageMaker endpoint and the attached resources
base_model_predictor.delete_model()
base_model_predictor.delete_endpoint()

4. Fine-tune the pre-trained model on a custom dataset

Fine-tuning refers to the process of taking a pre-trained language model and retraining it for a different but related task using specific data. This approach is also known as transfer learning, which involves transferring the knowledge learned from one task to another. Large language models (LLMs) like GPT-J 6B are trained on massive amounts of unlabeled data and can be fine-tuned on domain domain datasets, making the model perform better on that specific domain.

We will use financial text from SEC filings to fine tune a LLM GPT-J 6B for financial applications.

  • Input: A train and an optional validation directory. Each directory contains a CSV/JSON/TXT file.

    • For CSV/JSON files, the train or validation data is used from the column called ‘text’ or the first column if no column called ‘text’ is found.

    • The number of files under train and validation (if provided) should equal to one.

  • Output: A trained model that can be deployed for inference. Below is an example of a TXT file for fine-tuning the Text Generation model. The TXT file is SEC filings of Amazon from year 2021 to 2022.

SEC filings data of Amazon is downloaded from publicly available EDGAR. Instruction of accessing the data is shown here.

4.1. Retrieve 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.

[ ]:
from sagemaker import image_uris, model_uris, script_uris, hyperparameters

training_instance_type = "ml.g5.12xlarge"

# Retrieve the docker image
train_image_uri = image_uris.retrieve(
    region=None,
    framework=None,
    model_id=model_id,
    model_version=model_version,
    image_scope="training",
    instance_type=training_instance_type,
)
# Retrieve the training script
train_source_uri = script_uris.retrieve(
    model_id=model_id, model_version=model_version, script_scope="training"
)
# Retrieve the pre-trained model tarball to further fine-tune
train_model_uri = model_uris.retrieve(
    model_id=model_id, model_version=model_version, model_scope="training"
)

4.2. Set Training parameters

Now that we are done with all the setup that is needed, we are ready to fine-tune our Text Classification model. To begin, let us create a `sageMaker.estimator.Estimator <https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html>`__ 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. It is also used for sepcifying the model name if we want to fine-tune on the model which is not present in the dropdown list.

[ ]:
# Sample training data is available in this bucket
data_bucket = f"jumpstart-cache-prod-{aws_region}"
data_prefix = "training-datasets/sec_data"

training_dataset_s3_path = f"s3://{data_bucket}/{data_prefix}/train/"
validation_dataset_s3_path = f"s3://{data_bucket}/{data_prefix}/validation/"

output_bucket = sess.default_bucket()
output_prefix = "jumpstart-example-tg-train"

s3_output_location = f"s3://{output_bucket}/{output_prefix}/output"

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. ***

[ ]:
from sagemaker import hyperparameters

# Retrieve the default hyper-parameters for fine-tuning the model
hyperparameters = hyperparameters.retrieve_default(model_id=model_id, model_version=model_version)

# [Optional] Override default hyperparameters with custom values
hyperparameters["epoch"] = "3"
hyperparameters["per_device_train_batch_size"] = "4"
print(hyperparameters)

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. ***

[ ]:
from sagemaker.tuner import ContinuousParameter

# Use AMT for tuning and selecting the best model
use_amt = False

# Define objective metric, based on which the best model will be selected.
amt_metric_definitions = {
    "metrics": [{"Name": "eval:loss", "Regex": "'eval_loss': ([0-9]+\.[0-9]+)"}],
    "type": "Minimize",
}

# You can select from the hyperparameters supported by the model, and configure ranges of values to be searched for training the optimal model.(https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-define-ranges.html)
hyperparameter_ranges = {
    "learning_rate": ContinuousParameter(0.00001, 0.0001, scaling_type="Logarithmic")
}

# Increase the total number of training jobs run by AMT, for increased accuracy (and training time).
max_jobs = 6
# Change parallel training jobs run by AMT to reduce total training time, constrained by your account limits.
# if max_jobs=max_parallel_jobs then Bayesian search turns to Random.
max_parallel_jobs = 2

4.4. Start Training


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

[ ]:
from sagemaker.estimator import Estimator
from sagemaker.utils import name_from_base
from sagemaker.tuner import HyperparameterTuner

training_job_name = name_from_base(f"jumpstart-example-{model_id}-transfer-learning")

metric_definitions = [
    {"Name": "train:loss", "Regex": "'loss': ([0-9]+\.[0-9]+)"},
    {"Name": "eval:loss", "Regex": "'eval_loss': ([0-9]+\.[0-9]+)"},
    {"Name": "eval:runtime", "Regex": "'eval_runtime': ([0-9]+\.[0-9]+)"},
    {"Name": "eval:samples_per_second", "Regex": "'eval_samples_per_second': ([0-9]+\.[0-9]+)"},
    {"Name": "eval:eval_steps_per_second", "Regex": "'eval_steps_per_second': ([0-9]+\.[0-9]+)"},
]


# Create SageMaker Estimator instance
tg_estimator = Estimator(
    role=aws_role,
    image_uri=train_image_uri,
    source_dir=train_source_uri,
    model_uri=train_model_uri,
    entry_point="transfer_learning.py",
    instance_count=1,
    instance_type=training_instance_type,
    max_run=360000,
    hyperparameters=hyperparameters,
    output_path=s3_output_location,
    base_job_name=training_job_name,
    metric_definitions=metric_definitions,
)

if use_amt:
    hp_tuner = HyperparameterTuner(
        tg_estimator,
        amt_metric_definitions["metrics"][0]["Name"],
        hyperparameter_ranges,
        amt_metric_definitions["metrics"],
        max_jobs=max_jobs,
        max_parallel_jobs=max_parallel_jobs,
        objective_type=amt_metric_definitions["type"],
        base_tuning_job_name=training_job_name,
    )

    # Launch a SageMaker Tuning job to search for the best hyperparameters
    hp_tuner.fit({"train": training_dataset_s3_path, "validation": validation_dataset_s3_path})
else:
    # Launch a SageMaker Training job by passing s3 path of the training data
    tg_estimator.fit(
        {"train": training_dataset_s3_path, "validation": validation_dataset_s3_path}, logs=True
    )

4.5. Extract Training performance metrics


Performance metrics such as training loss and validation accuracy/loss can be accessed through cloudwatch while the training. We can also fetch these metrics and analyze them within the notebook ***

[ ]:
from sagemaker import TrainingJobAnalytics

if use_amt:
    training_job_name = hp_tuner.best_training_job()
else:
    training_job_name = tg_estimator.latest_training_job.job_name

df = TrainingJobAnalytics(training_job_name=training_job_name).dataframe()
df.head(10)

4.6. 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 artifacts for deploying an endpoint. However, instead of base_predictor, we deploy the tg_estimator that we fine-tuned. ***

[ ]:
inference_instance_type = "ml.g5.12xlarge"

# Retrieve the inference docker container uri
deploy_image_uri = image_uris.retrieve(
    region=None,
    framework=None,
    image_scope="inference",
    model_id=model_id,
    model_version=model_version,
    instance_type=inference_instance_type,
)

endpoint_name_after_finetune = name_from_base(f"jumpstart-example-{model_id}-")

# Use the estimator from the previous step to deploy to a SageMaker endpoint
finetuned_predictor = (hp_tuner if use_amt else tg_estimator).deploy(
    initial_instance_count=1,
    instance_type=inference_instance_type,
    image_uri=deploy_image_uri,
    endpoint_name=endpoint_name_after_finetune,
)

Next, we query the finetuned model using the same set of examples above, parse the response and print the predictions.

[ ]:
import json
import boto3


def query_endpoint_with_json_payload(encoded_json, endpoint_name):
    client = boto3.client("runtime.sagemaker")
    response = client.invoke_endpoint(
        EndpointName=endpoint_name, ContentType="application/json", Body=encoded_json
    )
    return response


def parse_response_multiple_texts(query_response):
    generated_text = []
    model_predictions = json.loads(query_response["Body"].read())
    return model_predictions[0]

The outputs from fine-tune model are generated as below. We can see that after being fine-tuned, the model can generate more insightful contents related to financial domain.

[ ]:
parameters = {
    "max_length": 400,
    "num_return_sequences": 1,
    "top_k": 250,
    "top_p": 0.8,
    "do_sample": True,
    "temperature": 1,
}

res_gpt_finetune = []
for quota_text in [
    "This Form 10-K report shows that",
    "We serve consumers through",
    "Our vision is",
]:
    payload = {"text_inputs": f"{quota_text}:", **parameters}

    query_response = query_endpoint_with_json_payload(
        json.dumps(payload).encode("utf-8"), endpoint_name_after_finetune
    )
    generated_texts = parse_response_multiple_texts(query_response)[0]["generated_text"]
    res_gpt_finetune.append(generated_texts)
    print(generated_texts)
    print("\n")

We compare the outputs between the model before fine-tuning and after fine-tuning.

[ ]:
import pandas as pd

pd.DataFrame(
    {
        "Input example": [
            "This Form 10-K report shows that",
            "We serve consumers through",
            "Our vision is",
        ],
        "Output before finetuning": res_gpt_before_finetune,
        "Output after finetuning": res_gpt_finetune,
    }
)
[ ]:
# Delete the SageMaker endpoint and the attached resources
finetuned_predictor.delete_model()
finetuned_predictor.delete_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