Deploy your finetuned model on AWS Marketplace

Youran QiYouran Qi

Deploy Your Own Finetuned Command-R-0824 Model from AWS Marketplace

This sample notebook shows you how to deploy your own finetuned HuggingFace Command-R model CohereForAI/c4ai-command-r-08-2024 using Amazon SageMaker. More specifically, assuming you already have the adapter weights or merged weights from your own finetuning of CohereForAI/c4ai-command-r-08-2024, we will show you how to

  1. Merge the adapter weights to the weights of the base model, if you bring only the adapter weights
  2. Export the merged weights to the TensorRT-LLM inference engine using Amazon SageMaker
  3. Deploy the engine as a SageMaker endpoint to serve your business use cases

Note: This is a reference notebook and it cannot run unless you make changes suggested in the notebook.

Pre-requisites:

  1. Note: This notebook contains elements which render correctly in Jupyter interface. Open this notebook from an Amazon SageMaker Notebook Instance or Amazon SageMaker Studio.
  2. Ensure that IAM role used has AmazonSageMakerFullAccess
  3. To deploy this ML model successfully, ensure that:
    1. Either your IAM role has these three permissions and you have authority to make AWS Marketplace subscriptions in the AWS account used:
      1. aws-marketplace:ViewSubscriptions
      2. aws-marketplace:Unsubscribe
      3. aws-marketplace:Subscribe
    2. or your AWS account has a subscription to the packages for Cohere Bring Your Own Fine-tuning. If so, skip step: Subscribe to the bring your own finetuning algorithm

Contents:

  1. Subscribe to the bring your own finetuning algorithm
  2. Preliminary setup
  3. Get the merged weights
  4. Upload the merged weights to S3
  5. Export the merged weights to the TensorRT-LLM inference engine
  6. Create an endpoint for inference from the exported engine
  7. Perform real-time inference by calling the endpoint
  8. Delete the endpoint (optional)
  9. Unsubscribe to the listing (optional)

Usage instructions:

You can run this notebook one cell at a time (By using Shift+Enter for running a cell).

1. Subscribe to the bring your own finetuning algorithm

To subscribe to the algorithm:

  1. Open the algorithm listing page Cohere Bring Your Own Fine-tuning.
  2. On the AWS Marketplace listing, click on the Continue to Subscribe button.
  3. On the Subscribe to this software page, review and click on “Accept Offer” if you and your organization agrees with EULA, pricing, and support terms. On the “Configure and launch” page, make sure the ARN displayed in your region match with the ARN you will use below.

2. Preliminary setup

Install the Python packages you will use below and import them. For example, you can run the command below to install cohere if you haven’t done so.

1!pip install "cohere>=5.11.0"
1import cohere
2import os
3import sagemaker as sage
4
5from sagemaker.s3 import S3Uploader

Make sure you have access to the resources in your AWS account. For example, you can configure an AWS profile by the command aws configure sso (see here) and run the command below to set the environment variable AWS_PROFILE as your profile name.

1# Change "<aws_profile>" to your own AWS profile name
2os.environ["AWS_PROFILE"] = "<aws_profile>"

Finally, you need to set all the following variables using your own information. In general, do not add a trailing slash to these paths (otherwise some parts won’t work). You can use either ml.p4de.24xlarge or ml.p5.48xlarge as the instance_type for Cohere Bring Your Own Fine-tuning, but the instance_type used for export and inference (endpoint creation) must be identical.

1# The AWS region
2region = "<region>"
3
4# Get the arn of the bring your own finetuning algorithm by region
5cohere_package = (
6 "cohere-command-r-v2-byoft-8370167e649c32a1a5f00267cd334c2c"
7)
8algorithm_map = {
9 "us-east-1": f"arn:aws:sagemaker:us-east-1:865070037744:algorithm/{cohere_package}",
10 "us-east-2": f"arn:aws:sagemaker:us-east-2:057799348421:algorithm/{cohere_package}",
11 "us-west-2": f"arn:aws:sagemaker:us-west-2:594846645681:algorithm/{cohere_package}",
12 "eu-central-1": f"arn:aws:sagemaker:eu-central-1:446921602837:algorithm/{cohere_package}",
13 "ap-southeast-1": f"arn:aws:sagemaker:ap-southeast-1:192199979996:algorithm/{cohere_package}",
14 "ap-southeast-2": f"arn:aws:sagemaker:ap-southeast-2:666831318237:algorithm/{cohere_package}",
15 "ap-northeast-1": f"arn:aws:sagemaker:ap-northeast-1:977537786026:algorithm/{cohere_package}",
16 "ap-south-1": f"arn:aws:sagemaker:ap-south-1:077584701553:algorithm/{cohere_package}",
17}
18if region not in algorithm_map:
19 raise Exception(f"Current region {region} is not supported.")
20arn = algorithm_map[region]
21
22# The local directory of your adapter weights. No need to specify this, if you bring your own merged weights
23adapter_weights_dir = "<adapter_weights_dir>"
24
25# The local directory you want to save the merged weights. Or the local directory of your own merged weights, if you bring your own merged weights
26merged_weights_dir = "<merged_weights_dir>"
27
28# The S3 directory you want to save the merged weights
29s3_checkpoint_dir = "<s3_checkpoint_dir>"
30
31# The S3 directory you want to save the exported TensorRT-LLM engine. Make sure you do not reuse the same S3 directory across multiple runs
32s3_output_dir = "<s3_output_dir>"
33
34# The name of the export
35export_name = "<export_name>"
36
37# The name of the SageMaker endpoint
38endpoint_name = "<endpoint_name>"
39
40# The instance type for export and inference. Now "ml.p4de.24xlarge" and "ml.p5.48xlarge" are supported
41instance_type = "<instance_type>"

3. Get the merged weights

Assuming you use HuggingFace’s PEFT to finetune CohereForAI/c4ai-command-r-08-2024 and get the adapter weights, you can then merge your adapter weights to the base model weights to get the merged weights as shown below. Skip this step if you have already got the merged weights.

1import torch
2
3from peft import PeftModel
4from transformers import CohereForCausalLM
5
6
7def load_and_merge_model(
8 base_model_name_or_path: str, adapter_weights_dir: str
9):
10 """
11 Load the base model and the model finetuned by PEFT, and merge the adapter weights to the base weights to get a model with merged weights
12 """
13 base_model = CohereForCausalLM.from_pretrained(
14 base_model_name_or_path
15 )
16 peft_model = PeftModel.from_pretrained(
17 base_model, adapter_weights_dir
18 )
19 merged_model = peft_model.merge_and_unload()
20 return merged_model
21
22
23def save_hf_model(output_dir: str, model, tokenizer=None, args=None):
24 """
25 Save a HuggingFace model (and optionally tokenizer as well as additional args) to a local directory
26 """
27 os.makedirs(output_dir, exist_ok=True)
28 model.save_pretrained(
29 output_dir, state_dict=None, safe_serialization=True
30 )
31 if tokenizer is not None:
32 tokenizer.save_pretrained(output_dir)
33 if args is not None:
34 torch.save(
35 args, os.path.join(output_dir, "training_args.bin")
36 )
1# Get the merged model from adapter weights
2merged_model = load_and_merge_model(
3 "CohereForAI/c4ai-command-r-08-2024", adapter_weights_dir
4)
5
6# Save the merged weights to your local directory
7save_hf_model(merged_weights_dir, merged_model)

4. Upload the merged weights to S3

1%%time
2sess = sage.Session()
3merged_weights = S3Uploader.upload(merged_weights_dir, s3_checkpoint_dir, sagemaker_session=sess)
4print("merged_weights", merged_weights)

5. Export the merged weights to the TensorRT-LLM inference engine

Create Cohere client and use it to export the merged weights to the TensorRT-LLM inference engine. The exported TensorRT-LLM engine will be stored in a tar file {s3_output_dir}/{export_name}.tar.gz in S3, where the file name is the same as the export_name.

1%%time
2co = cohere.SagemakerClient(aws_region=region)
3co.sagemaker_finetuning.export_finetune(
4 arn=arn,
5 name=export_name,
6 s3_checkpoint_dir=s3_checkpoint_dir,
7 s3_output_dir=s3_output_dir,
8 instance_type=instance_type,
9 role="ServiceRoleSagemaker",
10)

6. Create an endpoint for inference from the exported engine

The Cohere client provides a built-in method to create an endpoint for inference, which will automatically deploy the model from the TensorRT-LLM engine you just exported.

1%%time
2co.sagemaker_finetuning.create_endpoint(
3 arn=arn,
4 endpoint_name=endpoint_name,
5 s3_models_dir=s3_output_dir,
6 recreate=True,
7 instance_type=instance_type,
8 role="ServiceRoleSagemaker",
9)

7. Perform real-time inference by calling the endpoint

Now, you can perform real-time inference by calling the endpoint you just deployed.

1# If the endpoint is already deployed, you can directly connect to it
2co.sagemaker_finetuning.connect_to_endpoint(
3 endpoint_name=endpoint_name
4)
5
6message = "Classify the following text as either very negative, negative, neutral, positive or very positive: mr. deeds is , as comedy goes , very silly -- and in the best way."
7result = co.sagemaker_finetuning.chat(message=message)
8print(result)

You can also evaluate your finetuned model using a evaluation dataset. The following is an example with the ScienceQA evaluation data at here.

1import json
2from tqdm import tqdm
3
4eval_data_path = "<path_to_scienceQA_eval.jsonl>"
5
6total = 0
7correct = 0
8for line in tqdm(open(eval_data_path).readlines()):
9 total += 1
10 question_answer_json = json.loads(line)
11 question = question_answer_json["messages"][0]["content"]
12 answer = question_answer_json["messages"][1]["content"]
13 model_ans = co.sagemaker_finetuning.chat(
14 message=question, temperature=0
15 ).text
16 if model_ans == answer:
17 correct += 1
18
19print(f"Accuracy of finetuned model is %.3f" % (correct / total))

8. Delete the endpoint (optional)

After you successfully performed the inference, you can delete the deployed endpoint to avoid being charged continuously.

1co.sagemaker_finetuning.delete_endpoint()
2co.sagemaker_finetuning.close()

9. Unsubscribe to the listing (optional)

If you would like to unsubscribe to the model package, follow these steps. Before you cancel the subscription, ensure that you do not have any deployable models created from the model package or using the algorithm. Note - You can find this information by looking at the container name associated with the model.

Steps to unsubscribe to product from AWS Marketplace:

  1. Navigate to Machine Learning tab on Your Software subscriptions page
  2. Locate the listing that you want to cancel the subscription for, and then choose Cancel Subscription to cancel the subscription.