Conference general chair and Amazon Scholar Yizhou Sun on modeling long-range dependencies, improving efficiency, and new causal models.Read More
Optimize data preparation with new features in AWS SageMaker Data Wrangler
Data preparation is a critical step in any data-driven project, and having the right tools can greatly enhance operational efficiency. Amazon SageMaker Data Wrangler reduces the time it takes to aggregate and prepare tabular and image data for machine learning (ML) from weeks to minutes. With SageMaker Data Wrangler, you can simplify the process of data preparation and feature engineering and complete each step of the data preparation workflow, including data selection, cleansing, exploration, and visualization from a single visual interface.
In this post, we explore the latest features of SageMaker Data Wrangler that are specifically designed to improve the operational experience. We delve into the support of Simple Storage Service (Amazon S3) manifest files, inference artifacts in an interactive data flow, and the seamless integration with JSON (JavaScript Object Notation) format for inference, highlighting how these enhancements make data preparation easier and more efficient.
Introducing new features
In this section, we discuss the SageMaker Data Wrangler’s new features for optimal data preparation.
S3 manifest file support with SageMaker Autopilot for ML inference
SageMaker Data Wrangler enables a unified data preparation and model training experience with Amazon SageMaker Autopilot in just a few clicks. You can use SageMaker Autopilot to automatically train, tune, and deploy models on the data that you’ve transformed in your data flow.
This experience is now further simplified with S3 manifest file support. An S3 manifest file is a text file that lists the objects (files) stored in an S3 bucket. If your exported dataset in SageMaker Data Wrangler is quite big and split into multiple-part data files in Amazon S3, now SageMaker Data Wrangler will automatically create a manifest file in S3 representing all these data files. This generated manifest file can now be used with the SageMaker Autopilot UI in SageMaker Data Wrangler to pick up all the partitioned data for training.
Before this feature launch, when using SageMaker Autopilot models trained on prepared data from SageMaker Data Wrangler, you could only choose one data file, which might not represent the entire dataset, especially if the dataset is very large. With this new manifest file experience, you’re not limited to a subset of your dataset. You can build an ML model with SageMaker Autopilot representing all your data using the manifest file and use that for your ML inference and production deployment. This feature enhances operational efficiency by simplifying training ML models with SageMaker Autopilot and streamlining data processing workflows.
Added support for inference flow in generated artifacts
Customers want to take the data transformations they’ve applied to their model training data, such as one-hot encoding, PCA, and impute missing values, and apply those data transformations to real-time inference or batch inference in production. To do so, you must have a SageMaker Data Wrangler inference artifact, which is consumed by a SageMaker model.
Previously, inference artifacts could only be generated from the UI when exporting to SageMaker Autopilot training or exporting an inference pipeline notebook. This didn’t provide flexibility if you wanted to take your SageMaker Data Wrangler flows outside of the Amazon SageMaker Studio environment. Now, you can generate an inference artifact for any compatible flow file through a SageMaker Data Wrangler processing job. This enables programmatic, end-to-end MLOps with SageMaker Data Wrangler flows for code-first MLOps personas, as well as an intuitive, no-code path to get an inference artifact by creating a job from the UI.
Streamlining data preparation
JSON has become a widely adopted format for data exchange in modern data ecosystems. SageMaker Data Wrangler’s integration with JSON format allows you to seamlessly handle JSON data for transformation and cleaning. By providing native support for JSON, SageMaker Data Wrangler simplifies the process of working with structured and semi-structured data, enabling you to extract valuable insights and prepare data efficiently. SageMaker Data Wrangler now supports JSON format for both batch and real-time inference endpoint deployment.
Solution overview
For our use case, we use the sample Amazon customer reviews dataset to show how SageMaker Data Wrangler can simplify the operational effort to build a new ML model using SageMaker Autopilot. The Amazon customer reviews dataset contains product reviews and metadata from Amazon, including 142.8 million reviews spanning May 1996 to July 2014.
On a high level, we use SageMaker Data Wrangler to manage this large dataset and perform the following actions:
- Develop an ML model in SageMaker Autopilot using all of the dataset, not just a sample.
- Build a real-time inference pipeline with the inference artifact generated by SageMaker Data Wrangler, and use JSON formatting for input and output.
S3 manifest file support with SageMaker Autopilot
When creating a SageMaker Autopilot experiment using SageMaker Data Wrangler, you could previously only specify a single CSV or Parquet file. Now you can also use an S3 manifest file, allowing you to use large amounts of data for SageMaker Autopilot experiments. SageMaker Data Wrangler will automatically partition input data files into several smaller files and generate a manifest that can be used in a SageMaker Autopilot experiment to pull in all the data from the interactive session, not just a small sample.
Complete the following steps:
- Import the Amazon customer review data from a CSV file into SageMaker Data Wrangler. Make sure to disable sampling when importing the data.
- Specify the transformations that normalize the data. For this example, remove symbols and transform everything into lowercase using SageMaker Data Wrangler’s built-in transformations.
- Choose Train model to start training.
To train a model with SageMaker Autopilot, SageMaker automatically exports data to an S3 bucket. For large datasets like this one, it will automatically break up the file into smaller files and generate a manifest that includes the location of the smaller files.
- First, select your input data.
Earlier, SageMaker Data Wrangler didn’t have an option to generate a manifest file to use with SageMaker Autopilot. Today, with the release of manifest file support, SageMaker Data Wrangler will automatically export a manifest file to Amazon S3, pre-fill the S3 location of the SageMaker Autopilot training with the manifest file S3 location, and toggle the manifest file option to Yes. No work is necessary to generate or use the manifest file.
- Configure your experiment by selecting the target for the model to predict.
- Next, select a training method. In this case, we select Auto and let SageMaker Autopilot decide the best training method based on the dataset size.
- Specify the deployment settings.
- Finally, review the job configuration and submit the SageMaker Autopilot experiment for training. When SageMaker Autopilot completes the experiment, you can view the training results and explore the best model.
Thanks to support for manifest files, you can use your entire dataset for the SageMaker Autopilot experiment, not just a subset of your data.
For more information on using SageMaker Autopilot with SageMaker Data Wrangler, see Unified data preparation and model training with Amazon SageMaker Data Wrangler and Amazon SageMaker Autopilot.
Generate inference artifacts from SageMaker Processing jobs
Now, let’s look at how we can generate inference artifacts through both the SageMaker Data Wrangler UI and SageMaker Data Wrangler notebooks.
SageMaker Data Wrangler UI
For our use case, we want to process our data through the UI and then use the resulting data to train and deploy a model through the SageMaker console. Complete the following steps:
- Open the data flow your created in the preceding section.
- Choose the plus sign next to the last transform, choose Add destination, and choose Amazon S3. This will be where the processed data will be stored.
- Choose Create job.
- Select Generate inference artifacts in the Inference parameters section to generate an inference artifact.
- For Inference artifact name, enter the name of your inference artifact (with .tar.gz as the file extension).
- For Inference output node, enter the destination node corresponding to the transforms applied to your training data.
- Choose Configure job.
- Under Job configuration, enter a path for Flow file S3 location. A folder called
data_wrangler_flows
will be created under this location, and the inference artifact will be uploaded to this folder. To change the upload location, set a different S3 location. - Leave the defaults for all other options and choose Create to create the processing job.
The processing job will create atarball (.tar.gz)
containing a modified data flow file with a newly added inference section that allows you to use it for inference. You need the S3 uniform resource identifier (URI) of the inference artifact to provide the artifact to a SageMaker model when deploying your inference solution. The URI will be in the form{Flow file S3 location}/data_wrangler_flows/{inference artifact name}.tar.gz
. - If you didn’t note these values earlier, you can choose the link to the processing job to find the relevant details. In our example, the URI is
s3://sagemaker-us-east-1-43257985977/data_wrangler_flows/example-2023-05-30T12-20-18.tar.gz.
- Copy the value of Processing image; we need this URI when creating our model, too.
- We can now use this URI to create a SageMaker model on the SageMaker console, which we can later deploy to an endpoint or batch transform job.
- Under Model settings¸ enter a model name and specify your IAM role.
- For Container input options, select Provide model artifacts and inference image location.
- For Location of inference code image, enter the processing image URI.
- For Location of model artifacts, enter the inference artifact URI.
- Additionally, if your data has a target column that will be predicted by a trained ML model, specify the name of that column under Environment variables, with
INFERENCE_TARGET_COLUMN_NAME
as Key and the column name as Value. - Finish creating your model by choosing Create model.
We now have a model that we can deploy to an endpoint or batch transform job.
SageMaker Data Wrangler notebooks
For a code-first approach to generate the inference artifact from a processing job, we can find the example code by choosing Export to on the node menu and choosing either Amazon S3, SageMaker Pipelines, or SageMaker Inference Pipeline. We choose SageMaker Inference Pipeline in this example.
In this notebook, there is a section titled Create Processor (this is identical in the SageMaker Pipelines notebook, but in the Amazon S3 notebook, the equivalent code will be under the Job Configurations section). At the bottom of this section is a configuration for our inference artifact called inference_params
. It contains the same information that we saw in the UI, namely the inference artifact name and the inference output node. These values will be prepopulated but can be modified. There is additionally a parameter called use_inference_params
, which needs to be set to True
to use this configuration in the processing job.
Further down is a section titled Define Pipeline Steps, where the inference_params
configuration is appended to a list of job arguments and passed into the definition for a SageMaker Data Wrangler processing step. In the Amazon S3 notebook, job_arguments
is defined immediately after the Job Configurations section.
With these simple configurations, the processing job created by this notebook will generate an inference artifact in the same S3 location as our flow file (defined earlier in our notebook). We can programmatically determine this S3 location and use this artifact to create a SageMaker model using the SageMaker Python SDK, which is demonstrated in the SageMaker Inference Pipeline notebook.
The same approach can be applied to any Python code that creates a SageMaker Data Wrangler processing job.
JSON file format support for input and output during inference
It’s pretty common for websites and applications to use JSON as request/response for APIs so that the information is easy to parse by different programming languages.
Previously, after you had a trained model, you could only interact with it via CSV as an input format in a SageMaker Data Wrangler inference pipeline. Today, you can use JSON as an input and output format, providing more flexibility when interacting with SageMaker Data Wrangler inference containers.
To get started with using JSON for input and output in the inference pipeline notebook, complete the follow steps:
- Define a payload.
For each payload, the model is expecting a key named instances. The value is a list of objects, each being its own data point. The objects require a key called features, and the values should be the features of a single data point that are intended to be submitted to the model. Multiple data points can be submitted in a single request, up to a total size of 6 MB per request.
See the following code:
- Specify the
ContentType
asapplication/json
. - Provide data to the model and receive inference in JSON format.
See Common Data Formats for Inference for sample input and output JSON examples.
Clean up
When you are finished using SageMaker Data Wrangler, we recommend that you shut down the instance it runs on to avoid incurring additional charges. For instructions on how to shut down the SageMaker Data Wrangler app and associated instance, see Shut Down Data Wrangler.
Conclusion
SageMaker Data Wrangler’s new features, including support for S3 manifest files, inference capabilities, and JSON format integration, transform the operational experience of data preparation. These enhancements streamline data import, automate data transformations, and simplify working with JSON data. With these features, you can enhance your operational efficiency, reduce manual effort, and extract valuable insights from your data with ease. Embrace the power of SageMaker Data Wrangler’s new features and unlock the full potential of your data preparation workflows.
To get started with SageMaker Data Wrangler, check out the latest information on the SageMaker Data Wrangler product page.
About the authors
Munish Dabra is a Principal Solutions Architect at Amazon Web Services (AWS). His current areas of focus are AI/ML and Observability. He has a strong background in designing and building scalable distributed systems. He enjoys helping customers innovate and transform their business in AWS. LinkedIn: /mdabra
Patrick Lin is a Software Development Engineer with Amazon SageMaker Data Wrangler. He is committed to making Amazon SageMaker Data Wrangler the number one data preparation tool for productionized ML workflows. Outside of work, you can find him reading, listening to music, having conversations with friends, and serving at his church.
Index your Alfresco content using the new Amazon Kendra Alfresco connector
Amazon Kendra is a highly accurate and simple-to-use intelligent search service powered by machine learning (ML). Amazon Kendra offers a suite of data source connectors to simplify the process of ingesting and indexing your content, wherever it resides.
Valuable data in organizations is stored in both structured and unstructured repositories. An enterprise search solution should be able to index and search across several structured and unstructured repositories.
Alfresco Content Services provides open, flexible, highly scalable enterprise content management (ECM) capabilities with the added benefits of a content services platform, making content accessible wherever and however you work through easy integrations with the business applications you use every day. Many organizations use the Alfresco content management platform to store their content. One of the key requirements for enterprise customers using Alfresco is the ability to easily and securely find accurate information across all the stored documents.
We are excited to announce that you can now use the new Amazon Kendra Alfresco connector to search documents stored in your Alfresco repositories and sites. In this post, we show how to use the new connector to retrieve documents stored in Alfresco for indexing purposes and securely use the Amazon Kendra intelligent search function. In addition, the ML-powered intelligent search can accurately find information from unstructured documents with natural language narrative content, for which keyword search is not very effective.
What’s new in the Amazon Kendra Alfresco connector
The Amazon Kendra Alfresco connector offers support for the following:
- Basic and OAuth2 authentication mechanisms for the Alfresco On-Premises (On-Prem) platform
- Basic and OAuth2 authentication mechanisms for the Alfresco PaaS platform
- Aspect-based crawling of Alfresco repository documents
Solution overview
With Amazon Kendra, you can configure multiple data sources to provide a central place to search across your document repositories and sites. The solution in this post demonstrates the following:
- Retrieval of documents and comments from Alfresco private sites and public sites
- Retrieval of documents and comments from Alfresco repositories using Amazon Kendra-specific aspects
- Authentication against Alfresco On-Prem and PaaS platforms using Basic and OAuth2 mechanisms, respectively
- The Amazon Kendra search capability with access control across sites and repositories
If you are going to use only one of the platforms, you can still follow this post to build the example solution; just ignore the steps corresponding to the platform that you are not using.
The following is a summary of the steps to build the example solution:
- Upload documents to the three Alfresco sites and the repository folder. Make sure the uploaded documents are unique across sites and repository folders.
- For the two private sites and repository, use document-level Alfresco permission management to set access permissions. For the public site, you don’t need to set up permissions at the document level. Note that permissions information is retrieved by the Amazon Kendra Alfresco connector and used for access control by the Amazon Kendra search function.
- For the two private sites and repository, create a new Amazon Kendra index (you use the same index for both the private sites and the repository). For the public site, create a new Amazon Kendra index.
- For the On-Prem private site, create an Amazon Kendra Alfresco data source using Basic authentication, within the Amazon Kendra index for private sites.
- For the On-Prem repository documents with Amazon Kendra-specific aspects, create a data source using Basic authentication, within the Amazon Kendra index for private sites.
- For the PaaS private site, create a data source using Basic authentication, within the Amazon Kendra index for private sites.
- For the PaaS public site, create a data source using OAuth2 authentication, within the Amazon Kendra index for public sites.
- Perform a sync for each data source.
- Run a test query in the Amazon Kendra index meant for private sites and the repository using access control.
- Run a test query in the Amazon Kendra index meant for public sites without access control.
Prerequisites
You need an AWS account with privileges to create AWS Identity and Access Management (IAM) roles and policies. For more information, see Overview of access management: Permissions and policies. You need to have a basic knowledge of AWS and how to navigate the AWS Management Console.
For the Alfresco On-Prem platform, complete the following steps:
- Create a private site or use an existing site.
- Create a repository folder or use an existing repository folder.
- Get the repository URL.
- Get Basic authentication credentials (user ID and password).
- Make sure authentication are part of the
ALFRESCO_ADMINISTRATORS
group. - Get the public X509 certificate in .pem format and save it locally.
For the Alfresco PaaS platform, complete the following steps:
- Create a private site or use an existing site.
- Create a public site or use an existing site.
- Get the repository URL.
- Get Basic authentication credentials (user ID and password).
- Get OAuth2 credentials (client ID, client secret, and token URL).
- Confirm that authentication users are part of the
ALFRESCO_ADMINISTRATORS
group.
Step 1: Upload example documents
Each uploaded document must have 5 MB or less in text. For more information, see Amazon Kendra Service Quotas. You can upload example documents or use existing documents within each site.
As shown in the following screenshot, we have uploaded four documents to the Alfresco On-Prem private site.
We have uploaded three documents to the Alfresco PaaS private site.
We have uploaded five documents to the Alfresco PaaS public site.
We have uploaded two documents to the Alfresco On-Prem repository.
Assign the aspect awskendra:indexControl
to one or more documents in the repository folder.
Step 2: Configure Alfresco permissions
Use the Alfresco Permissions Management feature to give access rights to example users for viewing uploaded documents. It is assumed that you have some example Alfresco user names, with email addresses, that can be used for setting permissions at the document level in private sites. These users are not used for crawling the sites.
In the following example for the On-Prem private site, we have provided users My Dev User1 and My Dev User2 with site-consumer access to the example document. Repeat the same procedure for the other uploaded documents.
In the following example for the PaaS private site, we have provided user Kendra User 3 with site-consumer access to the example document. Repeat the same procedure for the other uploaded documents.
For the Alfresco repository documents, we have provided user My Dev user1 with consumer access to the example document.
The following table lists the site or repository names, document names, and permissions.
Platform | Site or Repository Name | Document Name | User IDs |
On-Prem | MyAlfrescoSite | ChannelMarketingBudget.xlsx | My Manager User3 |
On-Prem | MyAlfrescoSite | wellarchitected-sustainability-pillar.pdf | My Dev User1, My Dev User2 |
On-Prem | MyAlfrescoSite | WorkDocs.docx | My Dev User1, My Dev User2, My Manager User3 |
On-Prem | MyAlfrescoSite | WorldPopulation.csv | My Dev User1, My Dev User2, My Manager User3 |
PaaS | MyAlfrescoCloudSite2 | DDoS_White_Paper.pdf | Kendra User3 |
PaaS | MyAlfrescoCloudSite2 | wellarchitected-framework.pdf | Kendra User3 |
PaaS | MyAlfrescoCloudSite2 | ML_Training.pptx | Kendra User1 |
PaaS | MyAlfrescoCloudPublicSite | batch_user.pdf | Everyone |
PaaS | MyAlfrescoCloudPublicSite | Amazon Simple Storage Service – User Guide.pdf | Everyone |
PaaS | MyAlfrescoCloudPublicSite | AWS Batch – User Guide.pdf | Everyone |
PaaS | MyAlfrescoCloudPublicSite | Amazon Detective.docx | Everyone |
PaaS | MyAlfrescoCloudPublicSite | Pricing.xlsx | Everyone |
On-Prem | Repo: MyAlfrescoRepoFolder1 | Polly-dg.pdf (aspect awskendra:indexControl) | My Dev User1 |
On-Prem | Repo: MyAlfrescoRepoFolder1 | Transcribe-api.pdf (aspect awskendra:indexControl) | My Dev User1 |
Step 3: Set up Amazon Kendra indexes
You can create a new Amazon Kendra index or use an existing index for indexing documents hosted in Alfresco private sites. To create a new index, complete the following steps:
- On the Amazon Kendra console, create an index called
Alfresco-Private
. - Create a new IAM role, then choose Next.
- For Access Control, choose Yes.
- For Token Type¸ choose JSON.
- Keep the user name and group as default.
- Choose None for user group expansion because we are assuming no integration with AWS IAM Identity Center (successor to AWS Single Sign-On).
- Choose Next.
- Choose Developer Edition for this example solution.
- Choose Create to create a new index.
The following screenshot shows the Alfresco-Private
index after it has been created.
- You can verify the access control configuration on the User access control tab.
- Repeat these steps to create a second index called
Alfresco-Public
.
Step 4: Create a data source for the On-Prem private site
To create a data source for the On-Prem private site, complete the following steps:
- On the Amazon Kendra console, navigate to the
Alfresco-Private
index. - Choose Data sources in the navigation pane.
- Choose Add data source.
- Choose Add connector for the Alfresco connector.
- For Data source name, enter
Alfresco-OnPrem-Private
. - Optionally, add a description.
- Keep the remaining settings as default and choose Next.
To connect to the Alfresco On-Prem site, the connector needs access to the public certificate corresponding to the On-Prem server. This was one of the prerequisites.
- Use a different browser tab to upload the .pem file to an Amazon Simple Storage Service (Amazon S3) bucket in your account.
You use this S3 bucket name in the next steps.
- Return to the data source creation page.
- For Source, select Alfresco server.
- For Alfresco repository URL, enter the repository URL (created as a prerequisite).
- For Alfresco user application URL, enter the same value as the repository URL.
- For SSL certificate location, choose Browse S3 and choose the S3 bucket where you uploaded the .pem file.
- For Authentication, select Basic authentication.
- For AWS Secrets Manager secret, choose Create and add new secret.
A pop-up window opens to create an AWS Secrets Manager secret.
- Enter a name for your secret, user name, and password, then choose Save.
- For Virtual Private Cloud (VPC), choose No VPC.
- Turn the identity crawler on.
- For IAM role, choose Create a new IAM role.
- Choose Next.
You can configure the data source to synchronize contents from one or more Alfresco sites. For this post, we sync to the on-prem private site.
- For Content to sync, select Single Alfresco site sync and choose
MyAlfrescoSite
. - Select Include comments to retrieve comments in addition to documents.
- For Sync mode, select Full sync.
- For Frequency, choose Run on demand (or a different frequency option as needed).
- Choose Next.
- Map the Alfresco document fields to the Amazon Kendra index fields (you can keep the defaults), then choose Next.
- On the Review and Create page, verify all the information, then choose Add data source.
After the data source has been created, the data source page is displayed as shown in the following screenshot.
Step 5: Create a data source for the On-Prem repository documents with Amazon Kendra-specific aspects
Similarly to the previous steps, create a data source for the On-Prem repository documents with Amazon Kendra-specific aspects:
- On the Amazon Kendra console, navigate to the
Alfresco-Private
index. - Choose Data sources in the navigation pane.
- Choose Add data source.
- Choose Add connector for the Alfresco connector.
- For Data source name, enter
Alfresco-OnPrem-Aspects
. - Optionally, add a description.
- Keep the remaining settings as default and choose Next.
- For Source, select Alfresco server.
- For Alfresco repository URL, enter the repository URL (created as a prerequisite).
- For Alfresco user application URL, enter the same value as the repository URL.
- For SSL certificate location, choose Browse S3 and choose the S3 bucket where you uploaded the .pem file.
- For Authentication, select Basic authentication.
- For AWS Secrets Manager secret, choose the secret you created earlier.
- For Virtual Private Cloud (VPC), choose No VPC.
- Turn the identity crawler off.
- For IAM role, choose Create a new IAM role.
- Choose Next.
For this scope, the connector retrieves only those On-Prem server repository documents that have been assigned an aspect called awskendra:indexControl
.
- For Content to sync, select Alfresco aspects sync.
- For Sync mode, select Full sync.
- For Frequency, choose Run on demand (or a different frequency option as needed).
- Choose Next.
- Map the Alfresco document fields to the Amazon Kendra index fields (you can keep the defaults), then choose Next.
- On the Review and Create page, verify all the information, then choose Add data source.
After the data source has been created, the data source page is displayed as shown in the following screenshot.
Step 6: Create a data source for the PaaS private site
Follow similar steps as the previous sections to create a data source for the PaaS private site:
- On the Amazon Kendra console, navigate to the
Alfresco-Private
index. - Choose Data sources in the navigation pane.
- Choose Add data source.
- Choose Add connector for the Alfresco connector.
- For Data source name, enter
Alfresco-Cloud-Private
. - Optionally, add a description.
- Keep the remaining settings as default and choose Next.
- For Source, select Alfresco cloud.
- For Alfresco repository URL, enter the repository URL (created as a prerequisite).
- For Alfresco user application URL, enter the same value as the repository URL.
- For Authentication, select Basic authentication.
- For AWS Secrets Manager secret, choose Create and add new secret.
- Enter a name for your secret, user name, and password, then choose Save.
- For Virtual Private Cloud (VPC), choose No VPC.
- Turn the identity crawler off.
- For IAM role, choose Create a new IAM role.
- Choose Next.
We can configure the data source to synchronize contents from one or more Alfresco sites. For this post, we configure the data source to sync from the PaaS private site MyAlfrescoCloudSite2
.
- For Content to sync, select Single Alfresco site sync and choose
MyAlfrescoCloudSite2
. - Select Include comments.
- For Sync mode, select Full sync.
- For Frequency, choose Run on demand (or a different frequency option as needed).
- Choose Next.
- Map the Alfresco document fields to the Amazon Kendra index fields (you can keep the defaults) and choose Next.
- On the Review and Create page, verify all the information, then choose Add data source.
After the data source has been created, the data source page is displayed as shown in the following screenshot.
Step 7: Create a data source for the PaaS public site
We follow similar steps as before to create a data source for the PaaS public site:
- On the Amazon Kendra console, navigate to the Alfresco-Public index.
- Choose Data sources in the navigation pane.
- Choose Add data source.
- Choose Add connector for the Alfresco connector.
- For Data source name, enter
Alfresco-Cloud-Public
. - Optionally, add a description.
- Keep the remaining settings as default and choose Next.
- For Source, select Alfresco cloud.
- For Alfresco repository URL, enter the repository URL (created as a prerequisite).
- For Alfresco user application URL, enter the same value as the repository URL.
- For Authentication, select OAuth2.0 authentication.
- For AWS Secrets Manager secret, choose Create and add new secret.
- Enter a name for your secret, client ID, client secret, and token URL, then choose Save.
- For Virtual Private Cloud (VPC), choose No VPC.
- Turn the identity crawler off.
- For IAM role, choose Create a new IAM role.
- Choose Next.
We configure this data source to sync to the PaaS public site MyAlfrescoCloudPublicSite
.
- For Content to sync, select Single Alfresco site sync and choose
MyAlfrescoCloudPublicSite
. - Optionally, select Include comments.
- For Sync mode, select Full sync.
- For Frequency, choose Run on demand (or a different frequency option as needed).
- Choose Next.
- Map the Alfresco document fields to the Amazon Kendra index fields (you can keep the defaults) and choose Next.
- On the Review and Create page, verify all the information, then choose Add data source.
After the data source has been created, the data source page is displayed as shown in the following screenshot.
Step 8: Perform a sync for each data source
Navigate to each of the data sources and choose Sync now. Complete only one synchronization at a time.
Wait for synchronization to be complete for all data sources. When each synchronization is complete for a data source, you see the status as shown in the following screenshot.
You can also view Amazon CloudWatch logs for a specific sync under Sync run history.
Step 9: Run a test query in the private index using access control
Now it’s time to test the solution. We first run a query in the private index using access control:
- On the Amazon Kendra console, navigate to the
Alfresco-Private
index and choose Search indexed content.
- Enter a query in the search field.
As shown in the following screenshot, Amazon Kendra didn’t return any results.
- Choose Apply token.
- Enter the email address corresponding to the My Dev User1 user and choose Apply.
Note that Amazon Kendra access control works based on the email address associated with an Alfresco user name.
- Run the search again.
The search results in a document list (containing wellarchitected-sustainability-pillar.pdf
in the following example) based on the access control setup.
If you run the same query again and provide an email address that doesn’t have access to either of these documents, you should not see these documents in the results list.
- Enter another query to search in the documents based on the aspect
awskendra:indexControl
. - Choose Apply token, enter the email address corresponding to My Dev User1 user, and choose Apply.
- Rerun the query.
Step 10: Run a test query in the public index without access control.
Similarly, we can test our solution by running queries in the public index without access control:
- On the Amazon Kendra console, navigate to the Alfresco-Public index and choose Search indexed content.
- Run a search query.
Because this example Alfresco public site has not been set up with any access control, we don’t use an access token.
Clean up
To avoid incurring future costs, clean up the resources you created as part of this solution. Delete newly added Alfresco data sources within the indexes. If you created new Amazon Kendra indexes while testing this solution, delete them as well.
Conclusion
With the new Alfresco connector for Amazon Kendra, organizations can tap into the repository of information stored in their account securely using intelligent search powered by Amazon Kendra.
To learn about these possibilities and more, refer to the Amazon Kendra Developer Guide. For more information on how you can create, modify, or delete metadata and content when ingesting your data from Alfresco, refer to Enriching your documents during ingestion and Enrich your content and metadata to enhance your search experience with custom document enrichment in Amazon Kendra.
About the Authors
Arun Anand is a Senior Solutions Architect at Amazon Web Services based in Houston area. He has 25+ years of experience in designing and developing enterprise applications. He works with partners in Energy & Utilities segment providing architectural and best practice recommendations for new and existing solutions.
Rajnish Shaw is a Senior Solutions Architect at Amazon Web Services, with a background as a Product Developer and Architect. Rajnish is passionate about helping customers build applications on the cloud. Outside of work Rajnish enjoys spending time with family and friends, and traveling.
Yuanhua Wang is a software engineer at AWS with more than 15 years of experience in the technology industry. His interests are software architecture and build tools on cloud computing.
Use the Amazon SageMaker and Salesforce Data Cloud integration to power your Salesforce apps with AI/ML
This post is co-authored by Daryl Martis, Director of Product, Salesforce Einstein AI.
This is the second post in a series discussing the integration of Salesforce Data Cloud and Amazon SageMaker. In Part 1, we show how the Salesforce Data Cloud and Einstein Studio integration with SageMaker allows businesses to access their Salesforce data securely using SageMaker and use its tools to build, train, and deploy models to endpoints hosted on SageMaker. The endpoints are then registered to the Salesforce Data Cloud to activate predictions in Salesforce.
In this post, we expand on this topic to demonstrate how to use Einstein Studio for product recommendations. You can use this integration for traditional models as well as large language models (LLMs).
Solution overview
In this post, we demonstrate how to create a predictive model in SageMaker to recommend the next best product to your customers by using historical data such as customer demographics, marketing engagements, and purchase history from Salesforce Data Cloud.
We use the following sample dataset. To use this dataset in your Data Cloud, refer to Create Amazon S3 Data Stream in Data Cloud.
The following attributes are needed to create the model:
- Club Member – If the customer is a club member
- Campaign – The campaign the customer is a part of
- State – The state or province the customer resides in
- Month – The month of purchase
- Case Count – The number of cases raised by the customer
- Case Type Return – Whether the customer returned any product within the last year
- Case Type Shipment Damaged – Whether the customer had any shipments damaged in the last year
- Engagement Score – The level of engagement the customer has (response to mailing campaigns, logins to the online store, and so on)
- Tenure – The tenure of the customer relationship with the company
- Clicks – The average number of clicks the customer has made within a week prior to purchase
- Pages Visited – The average number of pages the customer has visited within a week prior to purchase
- Product Purchased – The actual product purchased
- Id – The ID of the record
- DateTime – The timestamp of the dataset
The product recommendation model is built and deployed on SageMaker and is trained using data in the Salesforce Data Cloud. The following steps give an overview of how to use the new capabilities launched in SageMaker for Salesforce to enable the overall integration:
- Set up the Amazon SageMaker Studio domain and OAuth between Salesforce and the AWS account
s. - Use the newly launched capability of the Amazon SageMaker Data Wrangler connector for Salesforce Data Cloud to prepare the data in SageMaker without copying the data from Salesforce Data Cloud.
- Train a recommendation model in SageMaker Studio using training data that was prepared using SageMaker Data Wrangler.
- Package the SageMaker Data Wrangler container and the trained recommendation model container in an inference pipeline so the inference request can use the same data preparation steps you created to preprocess the training data. The real-time inference call data is first passed to the SageMaker Data Wrangler container in the inference pipeline, where it is preprocessed and passed to the trained model for product recommendation. For more information about this process, refer to New — Introducing Support for Real-Time and Batch Inference in Amazon SageMaker Data Wrangler. Although we use a specific algorithm to train the model in our example, you can use any algorithm that you find appropriate for your use case.
- Use the newly launched SageMaker provided project template for Salesforce Data Cloud integration to streamline implementing the preceding steps by providing the following templates:
- An example notebook showcasing data preparation, building, training, and registering the model.
- The SageMaker provided project template for Salesforce Data Cloud integration, which automates creating a SageMaker endpoint hosting the inference pipeline model. When a version of the model in the Amazon SageMaker Model Registry is approved, the endpoint is exposed as an API with Amazon API Gateway using a custom Salesforce JSON Web Token (JWT) authorizer. API Gateway is required to allow Salesforce Data Cloud to make predictions against the SageMaker endpoint using a JWT token that Salesforce creates and passes with the request when making predictions from Salesforce. JWT can be used as a part of OpenID Connect (OIDC) and OAuth 2.0 frameworks to restrict client access to your APIs.
- After you create the API, we recommend registering the model endpoint in Salesforce Einstein Studio. For instructions, refer to Bring Your Own AI Models to Salesforce with Einstein Studio
The following diagram illustrates the solution architecture.
Create a SageMaker Studio domain
First, create a SageMaker Studio domain. For instructions, refer to Onboard to Amazon SageMaker Domain. You should note down the domain ID and execution role that is created and will be used by your user profile. You add permissions to this role in subsequent steps.
The following screenshot shows the domain we created for this post.
The following screenshot shows the example user profile for this post.
Set up the Salesforce connected app
Next, we create a Salesforce connected app to enable the OAuth flow from SageMaker Studio to Salesforce Data Cloud. Complete the following steps:
- Log in to Salesforce and navigate to Setup.
- Search for App Manager and create a new connected app.
- Provide the following inputs:
- For Connected App Name, enter a name.
- For API Name, leave as default (it’s automatically populated).
- For Contact Email, enter your contact email address.
- Select Enable OAuth Settings.
- For Callback URL, enter
https://<domain-id>.studio.<region>.sagemaker.aws/jupyter/default/lab
, and provide the domain ID that you captured while creating the SageMaker domain and the Region of your SageMaker domain.
- Under Selected OAuth Scopes, move the following from Available OAuth Scopes to Selected OAuth Scopes and choose Save:
- Manage user data via APIs (api)
- Perform requests at any time (
refresh_token
,offline_access
) - Perform ANSI SQL queries on Salesforce Data Cloud data (Data Cloud_query_api)
- Manage Salesforce Customer Data Platform profile data (Data Cloud_profile_api
- Access the identity URL service (id, profile, email, address, phone)
- Access unique user identifiers (
openid
)
For more information about creating a connected app, refer to Create a Connected App.
- Return to the connected app and navigate to Consumer Key and Secret.
- Choose Manage Consumer Details.
- Copy the key and secret.
You may be asked to log in to your Salesforce org as part of the two-factor authentication here.
- Navigate back to the Manage Connected Apps page.
- Open the connected app you created and choose Manage.
- Choose Edit Policies and change IP Relaxation to Relax IP restrictions, then save your settings.
Configure SageMaker permissions and lifecycle rules
In this section, we walk through the steps to configure SageMaker permissions and lifecycle management rules.
Create a secret in AWS Secrets Manager
Enable OAuth integration with Salesforce Data Cloud by storing credentials from your Salesforce connected app in AWS Secrets Manager:
- On the Secrets Manager console, choose Store a new secret.
- Select Other type of secret.
- Create your secret with the following key-value pairs:
- Add a tag with the key
sagemaker:partner
and your choice of value. - Save the secret and note the ARN of the secret.
Configure a SageMaker lifecycle rule
The SageMaker Studio domain execution role will require AWS Identity and Access Management (IAM) permissions to access the secret created in the previous step. For more information, refer to Creating roles and attaching policies (console).
- On the IAM console, attach the following polices to their respective roles (these roles will be used by the SageMaker project for deployment):
- Add the policy
AmazonSageMakerPartnerServiceCatalogProductsCloudFormationServiceRolePolicy
to the service roleAmazonSageMakerServiceCatalogProductsCloudformationRole
. - Add the policy
AmazonSageMakerPartnerServiceCatalogProductsApiGatewayServiceRolePolicy
to the service roleAmazonSageMakerServiceCatalogProductsApiGatewayRole
. - Add the policy
AmazonSageMakerPartnerServiceCatalogProductsLambdaServiceRolePolicy
to the service roleAmazonSageMakerServiceCatalogProductsLambdaRole
.
- Add the policy
- On the IAM console, navigate to the SageMaker domain execution role.
- Choose Add permissions and select Create an inline policy.
- Enter the following policy in the JSON policy editor:
SageMaker Studio lifecycle configuration provides shell scripts that run when a notebook is created or started. The lifecycle configuration will be used to retrieve the secret and import it to the SageMaker runtime.
- On the SageMaker console, choose Lifecycle configurations in the navigation pane.
- Choose Create configuration.
- Leave the default selection Jupyter Server App and choose Next.
- Give the configuration a name.
- Enter the following script in the editor, providing the ARN for the secret you created earlier:
- Choose Submit to save the lifecycle configuration.
- Choose Domains in the navigation pane and open your domain.
- On the Environment tab, choose Attach to attach your lifecycle configuration.
- Choose the lifecycle configuration you created and choose Attach to domain.
- Choose Set as default.
If you are a returning user to SageMaker Studio, in order to ensure Salesforce Data Cloud is enabled, upgrade to the latest Jupyter and SageMaker Data Wrangler kernels.
This completes the setup to enable data access from Salesforce Data Cloud to SageMaker Studio to build AI and machine learning (ML) models.
Create a SageMaker project
To start using the solution, first create a project using Amazon SageMaker Projects. Complete the following steps:
- In SageMaker Studio, under Deployments in the navigation pane, choose Projects.
- Choose Create project.
- Choose the project template called Model deployment for Salesforce.
- Choose Select project template.
- Enter a name and optional description for your project.
- Enter a model group name.
- Enter the name of the Secrets Manager secret that you created earlier.
- Choose Create project.
The project may take 1–2 minutes to initiate.
You can see two new repositories. The first one is for sample notebooks that you can use as is or customize to prepare, train, create, and register models in the SageMaker Model Registry. The second repository is for automating the model deployment, which includes exposing the SageMaker endpoint as an API.
- Choose clone repo for both notebooks.
For this post, we use the product recommendation example, which can be found in the sagemaker-<YOUR-PROJECT-NAME>-p-<YOUR-PROJECT-ID>-example-nb/product-recommendation
directory that you just cloned. Before we run the product-recommendation.ipynb notebook, let’s do some data preparation to create the training data using SageMaker Data Wrangler.
Prepare data with SageMaker Data Wrangler
Complete the following steps:
- In SageMaker Studio, on the File menu, choose New and Data Wrangler flow.
- After you create the data flow, choose (right-click) the tab and choose Rename to rename the file.
- Choose Import data.
- Choose Create connection.
- Choose Salesforce Data Cloud.
- For Name, enter
salesforce-data-cloud-sagemaker-connection
. - For Salesforce org URL, enter your Salesforce org URL.
- Choose Save + Connect.
- In the Data Explorer view, select and preview the tables from the Salesforce Data Cloud to create and run the query to extract the required dataset.
- Your query will look like below and you may use the table name that you used while uploading data in Salesforce Data Cloud.
- Choose Create dataset.
Creating the dataset may take some time.
In the data flow view, you can now see a new node added to the visual graph.
For more information on how you can use SageMaker Data Wrangler to create Data Quality and Insights Reports, refer to Get Insights On Data and Data Quality.
SageMaker Data Wrangler offers over 300 built-in transformations. In this step, we use some of these transformations to prepare the dataset for an ML model. For detailed instructions on how to implement these transformations, refer to Transform Data.
- Use the Manage columns step with the Drop column transform to drop the column
id__c
. - Use the Handle missing step with the Drop missing transform to drop rows with missing values for various features. We apply this transformation on all columns.
- Use a custom transform step to create categorical values for
state__c
,case_count__c
, andtenure
features. Use the following code for this transformation: - Use the Process numeric step with the Scale values transform and choose Standard scaler to scale
clicks__c
,engagement__score
, andpages__visited__c
features. - Use the Encode categorical step with the One-hot encode transform to convert categorical variables to numeric for
case__type__return___c
,case__type_shipment__damaged
,month__c
,club__member__c
, andcampaign__c
features (all features exceptclicks__c
,engagement__score
,pages__visited__c
, andproduct_purchased__c
).
Model building, training, and deployment
To build, train, and deploy the model, complete the following steps:
- Return to the SageMaker project, open the product-recommendation.ipynb notebook, and run a processing job to preprocess the data using the SageMaker Data Wrangler configuration you created.
- Follow the steps in the notebook to train a model and register it to the SageMaker Model Registry.
- Make sure to update the model group name to match with the model group name that you used while creating the SageMaker project.
To locate the model group name, open the SageMaker project that you created earlier and navigate to the Settings tab.
Similarly, the flow file referenced in the notebook must match with the flow file name that you created earlier.
- For this post, we used
product-recommendation
as the model group name, so we update the notebook withproject-recommendation
as the model group name in the notebook.
After the notebook is run, the trained model is registered in the Model Registry. To learn more about the Model Registry, refer to Register and Deploy Models with Model Registry.
- Select the model version you created and update the status of it to Approved.
Now that you have approved the registered model, the SageMaker Salesforce project deploy step will provision and trigger AWS CodePipeline.
CodePipeline has steps to build and deploy a SageMaker endpoint for inference containing the SageMaker Data Wrangler preprocessing steps and the trained model. The endpoint will be exposed to Salesforce Data Cloud as an API through API Gateway. The following screenshot shows the pipeline prefixed with Sagemaker-salesforce-product-recommendation-xxxxx
. We also show you the endpoints and API that gets created by the SageMaker project for Salesforce.
If you would like, you can take a look at the CodePipeline deploy step, which uses AWS CloudFormation scripts to create SageMaker endpoint and API Gateway with a custom JWT authorizer.
When pipeline deployment is complete, you can find the SageMaker endpoint on the SageMaker console.
You can explore the API Gateway created by the project template on the API Gateway console.
Choose the link to find the API Gateway URL.
You can find the details of the JWT authorizer by choosing Authorizers on the API Gateway console. You can also go to the AWS Lambda console to review the code of the Lambda function created by project template.
To discover the schema to be used while invoking the API from Einstein Studio, choose Information in the navigation pane of the Model Registry. You will see an Amazon Simple Storage Service (Amazon S3) link to a metadata file. Copy and paste the link into a new browser tab URL.
Let’s look at the file without downloading it. On the file details page, choose the Object actions menu and choose Query with S3 Select.
Choose Run SQL query and take note of the API Gateway URL and schema because you will need this information when registering with Einstein Studio. If you don’t see an APIGWURL
key, either the model wasn’t approved, deployment is still in progress, or deployment failed.
Use the Salesforce Einstein Studio API for predictions
Salesforce Einstein Studio is a new and centralized experience in Salesforce Data Cloud that data science and engineering teams can use to easily access their traditional models and LLMs used in generative AI. Next, we set up the API URL and client_id
that you set in Secrets Manager earlier in Salesforce Einstein Studio to register and use the model inferences in Salesforce Einstein Studio. For instructions, refer to Bring Your Own AI Models to Salesforce with Einstein Studio.
Clean up
To delete all the resources created by the SageMaker project, on the project page, choose the Action menu and choose Delete.
To delete the resources (API Gateway and SageMaker endpoint) created by CodePipeline, navigate to the AWS CloudFormation console and delete the stack that was created.
Conclusion
In this post, we explained how you can build and train ML models in SageMaker Studio using SageMaker Data Wrangler to import and prepare data that is hosted on the Salesforce Data Cloud and use the newly launched Salesforce Data Cloud JDBC connector in SageMaker Data Wrangler and first-party Salesforce template in the SageMaker provided project template for Salesforce Data Cloud integration. The SageMaker project template for Salesforce enables you to deploy the model and create the endpoint and secure an API for a registered model. You then use the API to make predictions in Salesforce Einstein Studio for your business use cases.
Although we used the example of product recommendation to showcase the steps for implementing the end-to-end integration, you can use the SageMaker project template for Salesforce to create an endpoint and API for any SageMaker traditional model and LLM that is registered in the SageMaker Model Registry. We look forward to seeing what you build in SageMaker using data from Salesforce Data Cloud and empower your Salesforce applications using SageMaker hosted ML models!
This post is a continuation of the series regarding Salesforce Data Cloud and SageMaker integration. For a high-level overview and to learn more about the business impact you can make with this integration approach, refer to Part 1.
Additional resources
About the authors
Daryl Martis is the Director of Product for Einstein Studio at Salesforce Data Cloud. He has over 10 years of experience in planning, building, launching, and managing world-class solutions for enterprise customers including AI/ML and cloud solutions. He has previously worked in the financial services industry in New York City. Follow him on https://www.linkedin.com/in/darylmartis.
Rachna Chadha is a Principal Solutions Architect AI/ML in Strategic Accounts at AWS. Rachna is an optimist who believes that ethical and responsible use of AI can improve society in the future and bring economic and social prosperity. In her spare time, Rachna likes spending time with her family, hiking, and listening to music.
Ife Stewart is a Principal Solutions Architect in the Strategic ISV segment at AWS. She has been engaged with Salesforce Data Cloud over the last 2 years to help build integrated customer experiences across Salesforce and AWS. Ife has over 10 years of experience in technology. She is an advocate for diversity and inclusion in the technology field.
Dharmendra Kumar Rai (DK Rai) is a Sr. Data Architect, Data Lake & AI/ML, serving strategic customers. He works closely with customers to understand how AWS can help them solve problems, especially in the AI/ML and analytics space. DK has many years of experience in building data-intensive solutions across a range of industry verticals, including high-tech, FinTech, insurance, and consumer-facing applications.
Marc Karp is an ML Architect with the SageMaker Service team. He focuses on helping customers design, deploy, and manage ML workloads at scale. In his spare time, he enjoys traveling and exploring new places.
Bring your own AI using Amazon SageMaker with Salesforce Data Cloud
This post is co-authored by Daryl Martis, Director of Product, Salesforce Einstein AI.
We’re excited to announce Amazon SageMaker and Salesforce Data Cloud integration. With this capability, businesses can access their Salesforce data securely with a zero-copy approach using SageMaker and use SageMaker tools to build, train, and deploy AI models. The inference endpoints are connected with Data Cloud to drive predictions in real time. As a result, businesses can accelerate time to market while maintaining data integrity and security, and reduce the operational burden of moving data from one location to another.
Introducing Einstein Studio on Data Cloud
Data Cloud is a data platform that provides businesses with real-time updates of their customer data from any touch point. With Einstein Studio, a gateway to AI tools on the data platform, admins and data scientists can effortlessly create models with a few clicks or using code. Einstein Studio’s bring your own model (BYOM) experience provides the capability to connect custom or generative AI models from external platforms such as SageMaker to Data Cloud. Custom models can be trained using data from Salesforce Data Cloud accessed through the Amazon SageMaker Data Wrangler connector. Businesses can act on their predictions by seamlessly integrating custom models into Salesforce workflows, leading to improved efficiency, decision-making, and personalized experiences.
Benefits of the SageMaker and Data Cloud Einstein Studio integration
Here’s how using SageMaker with Einstein Studio in Salesforce Data Cloud can help businesses:
- It provides the ability to connect custom and generative AI models to Einstein Studio for various use cases, such as lead conversion, case classification, and sentiment analysis.
- It eliminates tedious, costly, and error-prone ETL (extract, transform, and load) jobs. The zero-copy approach to data reduces the overhead to manage data copies, reduces storage costs, and improves efficiencies.
- It provides access to highly curated, harmonized, and real-time data across Customer 360. This leads to expert models that deliver more intelligent predictions and business insights.
- It simplifies the consumption of results from business processes and drives value without latency. For example, you can use automated workflows that can adapt in an instant based on new data.
- It facilitates the operationalization of SageMaker models and inferences in Salesforce.
The following is an example of how to operationalize a SageMaker model using Salesforce Flow.
SageMaker integration
SageMaker is a fully managed service to prepare data and build, train, and deploy machine learning (ML) models for any use case with fully managed infrastructure, tools, and workflows.
To streamline the SageMaker and Salesforce Data Cloud integration, we are introducing two new capabilities in SageMaker:
- The SageMaker Data Wrangler Salesforce Data Cloud connector – With the newly launched SageMaker Data Wrangler Salesforce Data Cloud connector, admins can preconfigure connections to Salesforce to enable data analysts and data scientists to quickly access Salesforce data in real time and create features for ML. This will enable users to access Salesforce Data Cloud securely using OAuth. You can interactively visualize, analyze, and transform data using the power of Spark without writing any code using the low-code visual data preparation features of Salesforce Data Wrangler. You can also scale to process large datasets with SageMaker Processing jobs, train ML modes automatically using Amazon SageMaker Autopilot, and integrate with a SageMaker inference pipeline to deploy the same data flow to production with the inference endpoint to process data in real time or in batch for inference.
- The SageMaker Projects template for Salesforce – We launched a SageMaker Projects template for Salesforce that you can use to deploy endpoints for traditional and large language models (LLMs) and expose SageMaker endpoints as an API automatically. SageMaker Projects provides a straightforward way to set up and standardize the development environment for data scientists and ML engineers to build and deploy ML models on SageMaker.
Partner Quote
“The partnership between Salesforce and AWS Sagemaker will empower customers to leverage the power of AI (both, generative and non-generative models) across their Salesforce data sources, workflows and applications to deliver personalized experiences and power new content generation, summarization, and question-answer type experiences. By combining the best of both worlds, we are creating a new paradigm for data-driven innovation and customer success underpinned by AI.”
-Kaushal Kurapati, Salesforce Senior Vice President of Product, AI and Search
Solution overview
The BYOM integration solution provides customers with a native Salesforce Data Cloud connector in SageMaker Data Wrangler. The SageMaker Data Wrangler connector allows you to securely access Salesforce Data Cloud objects. Once users are authenticated, they can perform data exploration, preparation, and feature engineering tasks needed for model development and inference through the SageMaker Data Wrangler interactive visual interface. Data scientists can work within Amazon SageMaker Studio notebooks to develop custom models, which can be traditional or LLMs, and make them available for deployment by registering the model in the SageMaker Model Registry. When a model is approved for production in the registry, SageMaker Projects will automate the deployment of an invocation API that can be configured as a target in Salesforce Einstein Studio and integrated with Salesforce Customer 360 applications. The following diagram illustrates this architecture
Conclusion
In this post, we shared the SageMaker and Salesforce Einstein Studio BYOM integration, where you can use data in Salesforce Data Cloud to build and train traditional and LLMs in SageMaker. You can use SageMaker Data Wrangler to prepare data from Salesforce Data Cloud with zero copy. We also provided an automated solution to deploy the SageMaker endpoints as an API using a SageMaker Projects template for Salesforce.
AWS and Salesforce are excited to partner together to deliver this experience to our joint customers to help them drive business processes using the power of ML and artificial intelligence.
To learn more about the Salesforce BYOM integration, refer to Bring your own AI models with Einstein Studio. For a detailed implementation using product recommendations example use case, refer to Use the Amazon SageMaker and Salesforce Data Cloud integration to power your Salesforce Apps with AI/ML.
About the Authors
Daryl Martis is the Director of Product for Einstein Studio at Salesforce Data Cloud. He has over 10 years of experience in planning, building, launching, and managing world-class solutions for enterprise customers including AI/ML and cloud solutions. He has previously worked in the financial services industry in New York City.
Rachna Chadha is a Principal Solutions Architect AI/ML in Strategic Accounts at AWS. Rachna is an optimist who believes that the ethical and responsible use of AI can improve society in the future and bring economic and social prosperity. In her spare time, Rachna likes spending time with her family, hiking, and listening to music.
Ife Stewart is a Principal Solutions Architect in the Strategic ISV segment at AWS. She has been engaged with Salesforce Data Cloud over the last 2 years to help build integrated customer experiences across Salesforce and AWS. Ife has over 10 years of experience in technology. She is an advocate for diversity and inclusion in the technology field.
Maninder (Mani) Kaur is the AI/ML Specialist lead for Strategic ISVs at AWS. With her customer-first approach, Mani helps strategic customers shape their AI/ML strategy, fuel innovation, and accelerate their AI/ML journey. Mani is a firm believer of ethical and responsible AI, and strives to ensure that her customers’ AI solutions align with these principles.
Enhancing AWS intelligent document processing with generative AI
Data classification, extraction, and analysis can be challenging for organizations that deal with volumes of documents. Traditional document processing solutions are manual, expensive, error prone, and difficult to scale. AWS intelligent document processing (IDP), with AI services such as Amazon Textract, allows you to take advantage of industry-leading machine learning (ML) technology to quickly and accurately process data from any scanned document or image. Generative artificial intelligence (generative AI) complements Amazon Textract to further automate document processing workflows. Features such as normalizing key fields and summarizing input data support faster cycles for managing document process workflows, while reducing the potential for errors.
Generative AI is driven by large ML models called foundation models (FMs). FMs are transforming the way you can solve traditionally complex document processing workloads. In addition to existing capabilities, businesses need to summarize specific categories of information, including debit and credit data from documents such as financial reports and bank statements. FMs make it easier to generate such insights from the extracted data. To optimize time spent in human review and to improve employee productivity, mistakes such as missing digits in phone numbers, missing documents, or addresses without street numbers can be flagged in an automated way. In the current scenario, you need to dedicate resources to accomplish such tasks using human review and complex scripts. This approach is tedious and expensive. FMs can help complete these tasks faster, with fewer resources, and transform varying input formats into a standard template that can be processed further. At AWS, we offer services such as Amazon Bedrock, the easiest way to build and scale generative AI applications with FMs. Amazon Bedrock is a fully managed service that makes FMs from leading AI startups and Amazon available through an API, so you can find the model that best suits your requirements. We also offer Amazon SageMaker JumpStart, which allows ML practitioners to choose from a broad selection of open-source FMs. ML practitioners can deploy FMs to dedicated Amazon SageMaker instances from a network isolated environment and customize models using SageMaker for model training and deployment.
Ricoh offers workplace solutions and digital transformation services designed to help customers manage and optimize information flow across their businesses. Ashok Shenoy, VP of Portfolio Solution Development, says, “We are adding generative AI to our IDP solutions to help our customers get their work done faster and more accurately by utilizing new capabilities such as Q&A, summarization, and standardized outputs. AWS allows us to take advantage of generative AI while keeping each of our customers’ data separate and secure.”
In this post, we share how to enhance your IDP solution on AWS with generative AI.
Improving the IDP pipeline
In this section, we review how the traditional IDP pipeline can be augmented by FMs and walk through an example use case using Amazon Textract with FMs.
AWS IDP is comprised of three stages: classification, extraction, and enrichment. For more details about each stage, refer to Intelligent document processing with AWS AI services: Part 1 and Part 2. In the classification stage, FMs can now classify documents without any additional training. This means that documents can be categorized even if the model hasn’t seen similar examples before. FMs in the extraction stage normalize date fields and verify addresses and phone numbers, while ensuring consistent formatting. FMs in the enrichment stage allow inference, logical reasoning, and summarization. When you use FMs in each IDP stage, your workflow will be more streamlined and performance will improve. The following diagram illustrates the IDP pipeline with generative AI.
Extraction stage of the IDP pipeline
When FMs can’t directly process documents in their native formats (such as PDFs, img, jpeg, and tiff) as an input, a mechanism to convert documents to text is needed. To extract the text from the document before sending it to the FMs, you can use Amazon Textract. With Amazon Textract, you can extract lines and words and pass them to downstream FMs. The following architecture uses Amazon Textract for accurate text extraction from any type of document before sending it to FMs for further processing.
Typically, documents are comprised of structured and semi-structured information. Amazon Textract can be used to extract raw text and data from tables and forms. The relationship between the data in tables and forms plays a vital role in automating business processes. Certain types of information may not be processed by FMs. As a result, we can choose to either store this information in a downstream store or send it to FMs. The following figure is an example of how Amazon Textract can extract structured and semi-structured information from a document, in addition to lines of text that need to be processed by FMs.
Using AWS serverless services to summarize with FMs
The IDP pipeline we illustrated earlier can be seamlessly automated using AWS serverless services. Highly unstructured documents are common in big enterprises. These documents can span from Securities and Exchange Commission (SEC) documents in the banking industry to coverage documents in the health insurance industry. With the evolution of generative AI at AWS, people in these industries are looking for ways to get a summary from those documents in an automated and cost-effective manner. Serverless services help provide the mechanism to build a solution for IDP quickly. Services such as AWS Lambda, AWS Step Functions, and Amazon EventBridge can help build the document processing pipeline with integration of FMs, as shown in the following diagram.
The sample application used in the preceding architecture is driven by events. An event is defined as a change in state that has recently occurred. For example, when an object gets uploaded to an Amazon Simple Storage Service (Amazon S3) bucket, Amazon S3 emits an Object Created event. This event notification from Amazon S3 can trigger a Lambda function or a Step Functions workflow. This type of architecture is termed as an event-driven architecture. In this post, our sample application uses an event-driven architecture to process a sample medical discharge document and summarize the details of the document. The flow works as follows:
- When a document is uploaded to an S3 bucket, Amazon S3 triggers an Object Created event.
- The EventBridge default event bus propagates the event to Step Functions based on an EventBridge rule.
- The state machine workflow processes the document, beginning with Amazon Textract.
- A Lambda function transforms the analyzed data for the next step.
- The state machine invokes a SageMaker endpoint, which hosts the FM using direct AWS SDK integration.
- A summary S3 destination bucket receives the summary response gathered from the FM.
We used the sample application with a flan-t5 Hugging face model to summarize the following sample patient discharge summary using the Step Functions workflow.
The Step Functions workflow uses AWS SDK integration to call the Amazon Textract AnalyzeDocument and SageMaker runtime InvokeEndpoint APIs, as shown in the following figure.
This workflow results in a summary JSON object that is stored in a destination bucket. The JSON object looks as follows:
{
"summary": [
"John Doe is a 35-year old male who has been experiencing stomach problems for two months. He has been taking antibiotics for the last two weeks, but has not been able to eat much. He has been experiencing a lot of abdominal pain, bloating, and fatigue. He has also noticed a change in his stool color, which is now darker. He has been taking antacids for the last two weeks, but they no longer help. He has been experiencing a lot of fatigue, and has been unable to work for the last two weeks. He has also been experiencing a lot of abdominal pain, bloating, and fatigue. He has been taking antacids for the last two weeks, but they no longer help. He has been experiencing a lot of abdominal pain, bloating, and fatigue. He has been taking antacids for the last two weeks, but they no longer help. He has been experiencing a lot of abdominal pain, bloating, and fatigue. He has been taking antacids for the last two weeks, but they no longer help. He has been experiencing a lot of abdominal pain, bloating, and fatigue. He has been taking antacids for the last two weeks, but they no longer help."
],
"forms": [
{
"key": "Ph: ",
"value": "(888)-(999)-(0000) "
},
{
"key": "Fax: ",
"value": "(888)-(999)-(1111) "
},
{
"key": "Patient Name: ",
"value": "John Doe "
},
{
"key": "Patient ID: ",
"value": "NARH-36640 "
},
{
"key": "Gender: ",
"value": "Male "
},
{
"key": "Attending Physician: ",
"value": "Mateo Jackson, PhD "
},
{
"key": "Admit Date: ",
"value": "07-Sep-2020 "
},
{
"key": "Discharge Date: ",
"value": "08-Sep-2020 "
},
{
"key": "Discharge Disposition: ",
"value": "Home with Support Services "
},
{
"key": "Pre-existing / Developed Conditions Impacting Hospital Stay: ",
"value": "35 yo M c/o stomach problems since 2 months. Patient reports epigastric abdominal pain non- radiating. Pain is described as gnawing and burning, intermittent lasting 1-2 hours, and gotten progressively worse. Antacids used to alleviate pain but not anymore; nothing exacerbates pain. Pain unrelated to daytime or to meals. Patient denies constipation or diarrhea. Patient denies blood in stool but have noticed them darker. Patient also reports nausea. Denies recent illness or fever. He also reports fatigue for 2 weeks and bloating after eating. ROS: Negative except for above findings Meds: Motrin once/week. Tums previously. PMHx: Back pain and muscle spasms. No Hx of surgery. NKDA. FHx: Uncle has a bleeding ulcer. Social Hx: Smokes since 15 yo, 1/2-1 PPD. No recent EtOH use. Denies illicit drug use. Works on high elevation construction. Fast food diet. Exercises 3-4 times/week but stopped 2 weeks ago. "
},
{
"key": "Summary: ",
"value": "some activity restrictions suggested, full course of antibiotics, check back with physican in case of relapse, strict diet "
}
]
}
Generating these summaries using IDP with serverless implementation at scale helps organizations get meaningful, concise, and presentable data in a cost-effective way. Step Functions doesn’t limit the method of processing documents to one document at a time. Its distributed map feature can summarize large numbers of documents on a schedule.
The sample application uses a flan-t5 Hugging face model; however, you can use an FM endpoint of your choice. Training and running the model is out of scope of the sample application. Follow the instructions in the GitHub repository to deploy a sample application. The preceding architecture is a guidance on how you can orchestrate an IDP workflow using Step Functions. Refer to the IDP Generative AI workshop for detailed instructions on how to build an application with AWS AI services and FMs.
Set up the solution
Follow the steps in the README file to set the solution architecture (except for the SageMaker endpoints). After you have your own SageMaker endpoint available, you can pass the endpoint name as a parameter to the template.
Clean up
To save costs, delete the resources you deployed as part of the tutorial:
- Follow the steps in the cleanup section of the README file.
- Delete any content from your S3 bucket and then delete the bucket through the Amazon S3 console.
- Delete any SageMaker endpoints you may have created through the SageMaker console.
Conclusion
Generative AI is changing how you can process documents with IDP to derive insights. AWS AI services such as Amazon Textract along with AWS FMs can help accurately process any type of documents. For more information on working with generative AI on AWS, refer to Announcing New Tools for Building with Generative AI on AWS.
About the Authors
Sonali Sahu is leading intelligent document processing with the AI/ML services team in AWS. She is an author, thought leader, and passionate technologist. Her core area of focus is AI and ML, and she frequently speaks at AI and ML conferences and meetups around the world. She has both breadth and depth of experience in technology and the technology industry, with industry expertise in healthcare, the financial sector, and insurance.
Ashish Lal is a Senior Product Marketing Manager who leads product marketing for AI services at AWS. He has 9 years of marketing experience and has led the product marketing effort for Intelligent document processing. He got his Master’s in Business Administration at the University of Washington.
Mrunal Daftari is an Enterprise Senior Solutions Architect at Amazon Web Services. He is based in Boston, MA. He is a cloud enthusiast and very passionate about finding solutions for customers that are simple and address their business outcomes. He loves working with cloud technologies, providing simple, scalable solutions that drive positive business outcomes, cloud adoption strategy, and design innovative solutions and drive operational excellence.
Dhiraj Mahapatro is a Principal Serverless Specialist Solutions Architect at AWS. He specializes in helping enterprise financial services adopt serverless and event-driven architectures to modernize their applications and accelerate their pace of innovation. Recently, he has been working on bringing container workloads and practical usage of generative AI closer to serverless and EDA for financial services industry customers.
Jacob Hauskens is a Principal AI Specialist with over 15 years of strategic business development and partnerships experience. For the past 7 years, he has led the creation and implementation of go-to-market strategies for new AI-powered B2B services. Recently, he has been helping ISVs grow their revenue by adding generative AI to intelligent document processing workflows.
Leveraging transformers to improve product retrieval results
Assessing the absolute utility of query results, rather than just their relative utility, improves learning-to-rank models.Read More
Scale training and inference of thousands of ML models with Amazon SageMaker
As machine learning (ML) becomes increasingly prevalent in a wide range of industries, organizations are finding the need to train and serve large numbers of ML models to meet the diverse needs of their customers. For software as a service (SaaS) providers in particular, the ability to train and serve thousands of models efficiently and cost-effectively is crucial for staying competitive in a rapidly evolving market.
Training and serving thousands of models requires a robust and scalable infrastructure, which is where Amazon SageMaker can help. SageMaker is a fully managed platform that enables developers and data scientists to build, train, and deploy ML models quickly, while also offering the cost-saving benefits of using the AWS Cloud infrastructure.
In this post, we explore how you can use SageMaker features, including Amazon SageMaker Processing, SageMaker training jobs, and SageMaker multi-model endpoints (MMEs), to train and serve thousands of models in a cost-effective way. To get started with the described solution, you can refer to the accompanying notebook on GitHub.
Use case: Energy forecasting
For this post, we assume the role of an ISV company that helps their customers become more sustainable by tracking their energy consumption and providing forecasts. Our company has 1,000 customers who want to better understand their energy usage and make informed decisions about how to reduce their environmental impact. To do this, we use a synthetic dataset and train an ML model based on Prophet for each customer to make energy consumption forecasts. With SageMaker, we can efficiently train and serve these 1,000 models, providing our customers with accurate and actionable insights into their energy usage.
There are three features in the generated dataset:
- customer_id – This is an integer identifier for each customer, ranging from 0–999.
- timestamp – This is a date/time value that indicates the time at which the energy consumption was measured. The timestamps are randomly generated between the start and end dates specified in the code.
- consumption – This is a float value that indicates the energy consumption, measured in some arbitrary unit. The consumption values are randomly generated between 0–1,000 with sinusoidal seasonality.
Solution overview
To efficiently train and serve thousands of ML models, we can use the following SageMaker features:
- SageMaker Processing – SageMaker Processing is a fully managed data preparation service that enables you to perform data processing and model evaluation tasks on your input data. You can use SageMaker Processing to transform raw data into the format needed for training and inference, as well as to run batch and online evaluations of your models.
- SageMaker training jobs – You can use SageMaker training jobs to train models on a variety of algorithms and input data types, and specify the compute resources needed for training.
- SageMaker MMEs – Multi-model endpoints enable you to host multiple models on a single endpoint, which makes it easy to serve predictions from multiple models using a single API. SageMaker MMEs can save time and resources by reducing the number of endpoints needed to serve predictions from multiple models. MMEs support hosting of both CPU- and GPU-backed models. Note that in our scenario, we use 1,000 models, but this is not a limitation of the service itself.
The following diagram illustrates the solution architecture.
The workflow includes the following steps:
- We use SageMaker Processing to preprocess data and create a single CSV file per customer and store it in Amazon Simple Storage Service (Amazon S3).
- The SageMaker training job is configured to read the output of the SageMaker Processing job and distribute it in a round-robin fashion to the training instances. Note that this can also be achieved with Amazon SageMaker Pipelines.
- The model artifacts are stored in Amazon S3 by the training job, and are served directly from the SageMaker MME.
Scale training to thousands of models
Scaling the training of thousands of models is possible via the distribution
parameter of the TrainingInput class in the SageMaker Python SDK, which allows you to specify how data is distributed across multiple training instances for a training job. There are three options for the distribution
parameter: FullyReplicated
, ShardedByS3Key
, and ShardedByRecord
. The ShardedByS3Key
option means that the training data is sharded by S3 object key, with each training instance receiving a unique subset of the data, avoiding duplication. After the data is copied by SageMaker to the training containers, we can read the folder and files structure to train a unique model per customer file. The following is an example code snippet:
Every SageMaker training job stores the model saved in the /opt/ml/model
folder of the training container before archiving it in a model.tar.gz
file, and then uploads it to Amazon S3 upon training job completion. Power users can also automate this process with SageMaker Pipelines. When storing multiple models via the same training job, SageMaker creates a single model.tar.gz
file containing all the trained models. This would then mean that, in order to serve the model, we would need to unpack the archive first. To avoid this, we use checkpoints to save the state of individual models. SageMaker provides the functionality to copy checkpoints created during the training job to Amazon S3. Here, the checkpoints need to be saved in a pre-specified location, with the default being /opt/ml/checkpoints
. These checkpoints can be used to resume training at a later moment or as a model to deploy on an endpoint. For a high-level summary of how the SageMaker training platform manages storage paths for training datasets, model artifacts, checkpoints, and outputs between AWS Cloud storage and training jobs in SageMaker, refer to Amazon SageMaker Training Storage Folders for Training Datasets, Checkpoints, Model Artifacts, and Outputs.
The following code uses a fictitious model.save()
function inside the train.py
script containing the training logic:
Scale inference to thousands of models with SageMaker MMEs
SageMaker MMEs allow you to serve multiple models at the same time by creating an endpoint configuration that includes a list of all the models to serve, and then creating an endpoint using that endpoint configuration. There is no need to re-deploy the endpoint every time you add a new model because the endpoint will automatically serve all models stored in the specified S3 paths. This is achieved with Multi Model Server (MMS), an open-source framework for serving ML models that can be installed in containers to provide the front end that fulfills the requirements for the new MME container APIs. In addition, you can use other model servers including TorchServe and Triton. MMS can be installed in your custom container via the SageMaker Inference Toolkit. To learn more about how to configure your Dockerfile to include MMS and use it to serve your models, refer to Build Your Own Container for SageMaker Multi-Model Endpoints.
The following code snippet shows how to create an MME using the SageMaker Python SDK:
When the MME is live, we can invoke it to generate predictions. Invocations can be done in any AWS SDK as well as with the SageMaker Python SDK, as shown in the following code snippet:
When calling a model, the model is initially loaded from Amazon S3 on the instance, which can result in a cold start when calling a new model. Frequently used models are cached in memory and on disk to provide low-latency inference.
Conclusion
SageMaker is a powerful and cost-effective platform for training and serving thousands of ML models. Its features, including SageMaker Processing, training jobs, and MMEs, enable organizations to efficiently train and serve thousands of models at scale, while also benefiting from the cost-saving advantages of using the AWS Cloud infrastructure. To learn more about how to use SageMaker for training and serving thousands of models, refer to Process data, Train a Model with Amazon SageMaker and Host multiple models in one container behind one endpoint.
About the Authors
Davide Gallitelli is a Specialist Solutions Architect for AI/ML in the EMEA region. He is based in Brussels and works closely with customers throughout Benelux. He has been a developer since he was very young, starting to code at the age of 7. He started learning AI/ML at university, and has fallen in love with it since then.
Maurits de Groot is a Solutions Architect at Amazon Web Services, based out of Amsterdam. He likes to work on machine learning-related topics and has a predilection for startups. In his spare time, he enjoys skiing and playing squash.
Accelerate business outcomes with 70% performance improvements to data processing, training, and inference with Amazon SageMaker Canvas
Amazon SageMaker Canvas is a visual interface that enables business analysts to generate accurate machine learning (ML) predictions on their own, without requiring any ML experience or having to write a single line of code. SageMaker Canvas’s intuitive user interface lets business analysts browse and access disparate data sources in the cloud or on premises, prepare and explore the data, build and train ML models, and generate accurate predictions within a single workspace.
SageMaker Canvas allows analysts to use different data workloads to achieve the desired business outcomes with high accuracy and performance. The compute, storage, and memory requirements to generate accurate predictions are abstracted from the end-user, enabling them to focus on the business problem to be solved. Earlier this year, we announced performance optimizations based on customer feedback to deliver faster and more accurate model training times with SageMaker Canvas.
In this post, we show how SageMaker Canvas can now process data, train models, and generate predictions with increased speed and efficiency for different dataset sizes.
Prerequisites
If you would like to follow along, complete the following prerequisites:
- Have an AWS account.
- Set up SageMaker Canvas. For instructions, refer to Prerequisites for setting up Amazon SageMaker Canvas.
- Download the following two datasets to your local computer. The first is the NYC Yellow Taxi Trip dataset; the second is the eCommerce behavior data about retails events related to products and users.
Both datasets come under the Attribution 4.0 International (CC BY 4.0) license and are free to share and adapt.
Data processing improvements
With underlying performance optimizations, the time to import data into SageMaker Canvas has improved by over 70%. You can now import datasets of up to 2 GB in approximately 50 seconds and up to 5 GB in approximately 65 seconds.
After importing data, business analysts typically validate the data to ensure there are no issues found within the dataset. Example validation checks can be ensuring columns contain the correct data type, seeing if the value ranges are in line with expectations, making sure there is uniqueness in values where applicable, and others.
Data validation is now faster. In our tests, all validations took 50 seconds for the taxi dataset exceeding 5 GB in size, a 10-times improvement in speed.
Model training improvements
The performance optimizations related to ML model training in SageMaker Canvas now enable you to train models without running into potential out-of-memory requests failures.
The following screenshot shows the results of a successful build run using a large dataset the impact of the total_amount
feature on the target variable.
Inference improvements
Finally, SageMaker Canvas inference improvements achieved a 3.5 times reduction memory consumption in case of larger datasets in our internal testing.
Conclusion
In this post, we saw various improvements with SageMaker Canvas in importing, validation, training, and inference. We saw an increased in its ability to import large datasets by 70%. We saw a 10 times improvement in data validation, and a 3.5 times reduction in memory consumption. These improvements allow you to better work with large datasets and reduce time when building ML models with SageMaker Canvas.
We encourage you to experience the improvements yourself. We welcome your feedback as we continuously work on performance optimizations to improve the user experience.
About the authors
Peter Chung is a Solutions Architect for AWS, and is passionate about helping customers uncover insights from their data. He has been building solutions to help organizations make data-driven decisions in both the public and private sectors. He holds all AWS certifications as well as two GCP certifications. He enjoys coffee, cooking, staying active, and spending time with his family.
Tim Song is a Software Development Engineer at AWS SageMaker, with 10+ years of experience as software developer, consultant and tech leader he has demonstrated ability to deliver scalable and reliable products and solve complex problems. In his spare time, he enjoys the nature, outdoor running, hiking and etc.
Hariharan Suresh is a Senior Solutions Architect at AWS. He is passionate about databases, machine learning, and designing innovative solutions. Prior to joining AWS, Hariharan was a product architect, core banking implementation specialist, and developer, and worked with BFSI organizations for over 11 years. Outside of technology, he enjoys paragliding and cycling.
Maia Haile is a Solutions Architect at Amazon Web Services based in the Washington, D.C. area. In that role, she helps public sector customers achieve their mission objectives with well architected solutions on AWS. She has 5 years of experience spanning from nonprofit healthcare, Media and Entertainment, and retail. Her passion is leveraging intelligence (AI) and machine learning (ML) to help Public Sector customers achieve their business and technical goals.
Build and train computer vision models to detect car positions in images using Amazon SageMaker and Amazon Rekognition
Computer vision (CV) is one of the most common applications of machine learning (ML) and deep learning. Use cases range from self-driving cars, content moderation on social media platforms, cancer detection, and automated defect detection. Amazon Rekognition is a fully managed service that can perform CV tasks like object detection, video segment detection, content moderation, and more to extract insights from data without the need of any prior ML experience. In some cases, a more custom solution might be needed along with the service to solve a very specific problem.
In this post, we address areas where CV can be applied to use cases where the pose of objects, their position, and orientation is important. One such use case would be customer-facing mobile applications where an image upload is required. It might be for compliance reasons or to provide a consistent user experience and improve engagement. For example, on online shopping platforms, the angle at which products are shown in images has an effect on the rate of buying this product. One such case is to detect the position of a car. We demonstrate how you can combine well-known ML solutions with postprocessing to address this problem on the AWS Cloud.
We use deep learning models to solve this problem. Training ML algorithms for pose estimation requires a lot of expertise and custom training data. Both requirements are hard and costly to obtain. Therefore, we present two options: one that doesn’t require any ML expertise and uses Amazon Rekognition, and another that uses Amazon SageMaker to train and deploy a custom ML model. In the first option, we use Amazon Rekognition to detect the wheels of the car. We then infer the car orientation from the wheel positions using a rule-based system. In the second option, we detect the wheels and other car parts using the Detectron model. These are again used to infer the car position with rule-based code. The second option requires ML experience but is also more customizable. It can be used for further postprocessing on the image, for example, to crop out the whole car. Both of the options can be trained on publicly available datasets. Finally, we show how you can integrate this car pose detection solution into your existing web application using services like Amazon API Gateway and AWS Amplify.
Solution overview
The following diagram illustrates the solution architecture.
The solution consists of a mock web application in Amplify where a user can upload an image and invoke either the Amazon Rekognition model or the custom Detectron model to detect the position of the car. For each option, we host an AWS Lambda function behind an API Gateway that is exposed to our mock application. We configured our Lambda function to run with either the Detectron model trained in SageMaker or Amazon Rekognition.
Prerequisites
For this walkthrough, you should have the following prerequisites:
- An AWS account.
- An AWS Identity and Access Management (IAM) user with the permissions to deploy and provision the infrastructure, for example, PowerUserAccess (note that permissions would need to be restricted further for a production-ready application and depend on possible integrations with other services).
- Docker in your development environment (local machine or a SageMaker notebook instance where you are deploying the solution from).
- The AWS Cloud Development Kit (AWS CDK) installed. It can be installed using npm as explained in our GitHub repository.
Create a serverless app using Amazon Rekognition
Our first option demonstrates how you can detect car orientations in images using Amazon Rekognition. The idea is to use Amazon Rekognition to detect the location of the car and its wheels and then do postprocessing to derive the orientation of the car from this information. The whole solution is deployed using Lambda as shown in the Github repository. This folder contains two main files: a Dockerfile that defines the Docker image that will run in our Lambda function, and the app.py
file, which will be the main entry point of the Lambda function:
The Lambda function expects an event that contains a header and body, where the body should be the image needed to be labeled as base64 decoded object. Given the image, the Amazon Rekognition detect_labels
function is invoked from the Lambda function using Boto3. The function returns one or more labels for each object in the image and bounding box details for all of the detected object labels as part of the response, along with other information like confidence of the assigned label, the ancestor labels of the detected label, possible aliases for the label, and the categories the detected label belongs to. Based on the labels returned by Amazon Rekognition, we run the function label_image
, which calculates the car angle from the detected wheels as follows:
Note that the application requires that only one car is present in the image and returns an error if that’s not the case. However, the postprocessing can be adapted to provide more granular orientation descriptions, cover several cars, or calculate the orientation of more complex objects.
Improve wheel detection
To further improve the accuracy of the wheel detection, you can use Amazon Rekognition Custom Labels. Similar to fine-tuning using SageMaker to train and deploy a custom ML model, you can bring your own labeled data so that Amazon Rekognition can produce a custom image analysis model for you in just a few hours. With Rekognition Custom Labels, you only need a small set of training images that are specific to your use case, in this case car images with specific angles, because it uses the existing capabilities in Amazon Rekognition of being trained on tens of millions of images across many categories. Rekognition Custom Labels can be integrated with only a few clicks and small adaptations to the Lambda function we use for the standard Amazon Rekognition solution.
Train a model using a SageMaker training job
In our second option, we train a custom deep learning model on SageMaker. We use the Detectron2 framework for the segmentation of car parts. These segments are then used to infer the position of the car.
The Detectron2 framework is a library that provides state-of-the-art detection and segmentation algorithms. Detectron provides a variety of Mask R-CNN models that were trained on the famous COCO (Common objects in Context) dataset. To build our car objects detection model, we use transfer learning to fine-tune a pretrained Mask R-CNN model on the car parts segmentation dataset. This dataset allows us to train a model that can detect wheels but also other car parts. This additional information can be further used in the car angle computations relative to the image.
The dataset contains annotated data of car parts to be used for object detection and semantic segmentation tasks: approximately 500 images of sedans, pickups, and sports utility vehicles (SUVs), taken in multiple views (front, back, and side views). Each image is annotated by 18 instance masks and bounding boxes representing the different parts of a car like wheels, mirrors, lights, and front and back glass. We modified the base annotations of the wheels such that each wheel is considered an individual object instead of considering all the available wheels in the image as one object.
We use Amazon Simple Storage Service (Amazon S3) to store the dataset used for training the Detectron model along with the trained model artifacts. Moreover, the Docker container that runs in the Lambda function is stored in Amazon Elastic Container Registry (Amazon ECR). The Docker container in the Lambda function is needed to include the required libraries and dependencies for running the code. We could alternatively use Lambda layers, but it’s limited to an unzipped deployment packaged size quota of 250 MB and a maximum of five layers can be added to a Lambda function.
Our solution is built on SageMaker: we extend prebuilt SageMaker Docker containers for PyTorch to run our custom PyTorch training code. Next, we use the SageMaker Python SDK to wrap the training image into a SageMaker PyTorch estimator, as shown in the following code snippets:
Finally, we start the training job by calling the fit()
function on the created PyTorch estimator. When the training is finished, the trained model artifact is stored in the session bucket in Amazon S3 to be used for the inference pipeline.
Deploy the model using SageMaker and inference pipelines
We also use SageMaker to host the inference endpoint that runs our custom Detectron model. The full infrastructure used to deploy our solution is provisioned using the AWS CDK. We can host our custom model through a SageMaker real-time endpoint by calling deploy
on the PyTorch estimator. This is the second time we extend a prebuilt SageMaker PyTorch container to include PyTorch Detectron. We use it to run the inference script and host our trained PyTorch model as follows:
Note that we used an ml.g4dn.xlarge GPU for deployment because it’s the smallest GPU available and sufficient for this demo. Two components need to be configured in our inference script: model loading and model serving. The function model_fn()
is used to load the trained model that is part of the hosted Docker container and can also be found in Amazon S3 and return a model object that can be used for model serving as follows:
The function predict_fn()
performs the prediction and returns the result. Besides using our trained model, we use a pretrained version of the Mask R-CNN model trained on the COCO dataset to extract the main car in the image. This is an extra postprocessing step to deal with images where more than one car exists. See the following code:
Similar to the Amazon Rekognition solution, the bounding boxes predicted for the wheel
class are filtered from the detection outputs and supplied to the postprocessing module to assess the car position relative to the output.
Finally, we also improved the postprocessing for the Detectron solution. It also uses the segments of different car parts to infer the solution. For example, whenever a front bumper is detected, but no back bumper, it is assumed that we have a front view of the car and the corresponding angle is calculated.
Connect your solution to the web application
The steps to connect the model endpoints to Amplify are as follows:
- Clone the application repository that the AWS CDK stack created, named
car-angle-detection-website-repo
. Make sure you are looking for it in the Region you used for deployment. - Copy the API Gateway endpoints for each of the deployed Lambda functions into the
index.html
file in the preceding repository (there are placeholders where the endpoint needs to be placed). The following code is an example of what this section of the .html file looks like:
- Save the HTML file and push the code change to the remote main branch.
This will update the HTML file in the deployment. The application is now ready to use.
- Navigate to the Amplify console and locate the project you created.
The application URL will be visible after the deployment is complete.
- Navigate to the URL and have fun with the UI.
Conclusion
Congratulations! We have deployed a complete serverless architecture in which we used Amazon Rekognition, but also gave an option for your own custom model, with this example available on GitHub. If you don’t have ML expertise in your team or enough custom data to train a model, you could select the option that uses Amazon Rekognition. If you want more control over your model, would like to customize it further, and have enough data, you can choose the SageMaker solution. If you have a team of data scientists, they might also want to enhance the models further and pick a more custom and flexible option. You can put the Lambda function and the API Gateway behind your web application using either of the two options. You can also use this approach for a different use case for which you might want to adapt the code.
The advantage of this serverless architecture is that the building blocks are completely exchangeable. The opportunities are almost limitless. So, get started today!
As always, AWS welcomes feedback. Please submit any comments or questions.
About the Authors
Michael Wallner is a Senior Consultant Data & AI with AWS Professional Services and is passionate about enabling customers on their journey to become data-driven and AWSome in the AWS cloud. On top, he likes thinking big with customers to innovate and invent new ideas for them.
Aamna Najmi is a Data Scientist with AWS Professional Services. She is passionate about helping customers innovate with Big Data and Artificial Intelligence technologies to tap business value and insights from data. She has experience in working on data platform and AI/ML projects in the healthcare and life sciences vertical. In her spare time, she enjoys gardening and traveling to new places.
David Sauerwein is a Senior Data Scientist at AWS Professional Services, where he enables customers on their AI/ML journey on the AWS cloud. David focuses on digital twins, forecasting and quantum computation. He has a PhD in theoretical physics from the University of Innsbruck, Austria. He was also a doctoral and post-doctoral researcher at the Max-Planck-Institute for Quantum Optics in Germany. In his free time he loves to read, ski and spend time with his family.
Srikrishna Chaitanya Konduru is a Senior Data Scientist with AWS Professional services. He supports customers in prototyping and operationalising their ML applications on AWS. Srikrishna focuses on computer vision and NLP. He also leads ML platform design and use case identification initiatives for customers across diverse industry verticals. Srikrishna has an M.Sc in Biomedical Engineering from RWTH Aachen university, Germany, with a focus on Medical Imaging.
Ahmed Mansour is a Data Scientist at AWS Professional Services. He provide technical support for customers through their AI/ML journey on the AWS cloud. Ahmed focuses on applications of NLP to the protein domain along with RL. He has a PhD in Engineering from the Technical University of Munich, Germany. In his free time he loves to go to the gym and play with his kids.