Project Alexandria: Democratizing Scientific Knowledge Through Structu …

Scientific publishing has expanded significantly in recent decades, yet access to crucial research remains restricted for many, particularly in developing countries, independent researchers, and small academic institutions. The rising costs of journal subscriptions exacerbate this disparity, limiting the availability of knowledge even in well-funded universities. Despite the push for Open Access (OA), barriers persist, as demonstrated by large-scale access losses in Germany and the U.S. due to price disputes with publishers. This limitation hinders scientific progress, leading researchers to explore alternative methods for making scientific knowledge more accessible while navigating copyright constraints.

Current methods of accessing scientific content primarily involve direct subscriptions, institutional access, or reliance on legally ambiguous repositories. These approaches are either financially unsustainable or legally contentious. While OA publishing helps, it does not fully resolve the accessibility crisis. Large Language Models (LLMs) offer a new avenue for extracting and summarizing knowledge from scholarly texts, but their use raises copyright concerns. The challenge lies in separating factual content from the creative expressions protected under copyright law.

To address this, the research team proposes Project Alexandria, which introduces Knowledge Units (KUs) as a structured format for extracting factual information while omitting stylistic elements. KUs encode key scientific insights—such as definitions, relationships, and methodological details—in a structured database, ensuring that only non-copyrightable factual content is preserved. This framework aligns with legal principles like the idea-expression dichotomy, which states that facts cannot be copyrighted, only their specific phrasing and presentation.

Reference: https://arxiv.org/pdf/2502.19413

Knowledge Units are generated through an LLM pipeline that processes scholarly texts in paragraph-sized segments, extracting core concepts and their relationships. Each KU contains:

Entities: Core scientific concepts identified in the text.

Relationships: Connections between entities, including causal or definitional links.

Attributes: Specific details related to entities.

Context summary: A brief summary ensuring coherence across multiple KUs.

Sentence MinHash: A fingerprint to track the source text without storing the original phrasing.

This structured approach balances knowledge retention with legal defensibility. Paragraph-level segmentation ensures optimal granularity—too small, and information is scattered; too large, and LLM performance degrades.

From a legal standpoint, the framework complies with both German and U.S. copyright laws. German law explicitly excludes facts from copyright protection and allows data mining under specific exemptions. Similarly, the U.S. Fair Use doctrine permits transformative uses like text and data mining, provided they do not harm the market value of the original work. The research team demonstrates that KUs satisfy these legal conditions by excluding expressive elements while preserving factual content.

To evaluate the effectiveness of KUs, the team conducted multiple-choice question (MCQ) tests using abstracts and full-text articles from biology, physics, mathematics, and computer science. The results show that LLMs using KUs achieve nearly the same accuracy as those given the original texts. This suggests that the vast majority of relevant information is retained despite the removal of expressive elements. Furthermore, plagiarism detection tools confirm minimal overlap between KUs and the original texts, reinforcing the method’s legal viability.

Beyond legal considerations, the research explores the limitations of existing alternatives. Text embeddings, commonly used for knowledge representation, fail to capture precise factual details, making them unsuitable for scientific knowledge extraction. Direct paraphrasing methods risk maintaining too much similarity to the original text, potentially violating copyright laws. In contrast, KUs provide a more structured and legally sound approach.

The study also addresses common criticisms. While some argue that citation dilution could result from extracting knowledge into databases, traceable attribution systems can mitigate this concern. Others worry that nuances in scientific research may be lost, but the team highlights that most complex elements—like mathematical proofs—are not copyrightable to begin with. Concerns about potential legal risks and hallucination propagation are acknowledged, with recommendations for hybrid human-AI validation systems to enhance reliability.

The broader impact of freely accessible scientific knowledge extends across multiple sectors. Researchers can collaborate more effectively across disciplines, healthcare professionals can access critical medical research more efficiently, and educators can develop high-quality curricula without cost barriers. Additionally, open scientific knowledge promotes public trust and transparency, reducing misinformation and enabling informed decision-making.

Moving forward, the team identifies several research directions, including refining factual accuracy through cross-referencing, developing educational applications for KU-based knowledge dissemination, and establishing interoperability standards for knowledge graphs. They also propose integrating KUs into a broader semantic web for scientific discovery, leveraging AI to automate and validate extracted knowledge at scale.

In summary, Project Alexandria presents a promising framework for making scientific knowledge more accessible while respecting copyright constraints. By systematically extracting factual content from scholarly texts and structuring it into Knowledge Units, this approach provides a legally viable and technically effective solution to the accessibility crisis in scientific publishing. Extensive testing demonstrates its potential for preserving critical information without violating copyright laws, positioning it as a significant step toward democratizing access to knowledge in the scientific community.

Check out the Paper and Project. All credit for this research goes to the researchers of this project. Also, feel free to follow us on Twitter and don’t forget to join our 80k+ ML SubReddit.

Recommended Read- LG AI Research Releases NEXUS: An Advanced System Integrating Agent AI System and Data Compliance Standards to Address Legal Concerns in AI Datasets
The post Project Alexandria: Democratizing Scientific Knowledge Through Structured Fact Extraction with LLMs appeared first on MarkTechPost.

This AI Paper Identifies Function Vector Heads as Key Drivers of In-Co …

In-context learning (ICL) is something that allows large language models (LLMs) to generalize & adapt to new tasks with minimal demonstrations. ICL is crucial for improving model flexibility, efficiency, and application in language translation, text summarization, and automated reasoning. Despite its significance, the exact mechanisms responsible for ICL remain an active area of research, with two competing theories proposed: induction heads, which detect token sequences and predict subsequent tokens, and function vector (FV) heads, which encode a latent representation of tasks.

Understanding which mechanism predominantly drives ICL is a critical challenge. Induction heads function by identifying repeated patterns within input data and leveraging this repetition to predict forthcoming tokens. However, this approach does not fully explain how models perform complex reasoning with only a few examples. FV heads, on the other hand, are believed to capture an abstract understanding of tasks, providing a more generalized and adaptable approach to ICL. Differentiating between these two mechanisms and determining their contributions is essential for developing more efficient LLMs.

Earlier studies largely attributed ICL to induction heads, assuming their pattern-matching capability was fundamental to learning from context. However, recent research challenges this notion by demonstrating that FV heads play a more significant role in few-shot learning. While induction heads primarily operate at the syntactic level, FV heads enable a broader understanding of the relationships within prompts. This distinction suggests that FV heads may be responsible for the model’s ability to transfer knowledge across different tasks, a capability that induction heads alone cannot explain.

A research team from the University of California, Berkeley, conducted a study analyzing attention heads across twelve LLMs, ranging from 70 million to 7 billion parameters. They aimed to determine which attention heads play the most significant role in ICL. Through controlled ablation experiments, researchers disabled specific attention heads and measured the resulting impact on the model’s performance. By selectively removing either induction heads or FV heads, they could isolate each mechanism’s unique contributions.

The findings revealed that FV heads emerge later in the training process and are positioned in the model’s deeper layers than induction heads. Through detailed training analysis, researchers observed that many FV heads initially function as induction heads before transitioning into FV heads. This suggests that induction may be a precursor to developing more complex FV mechanisms. This transformation was noted across multiple models, indicating a consistent pattern in how LLMs develop task comprehension over time.

Performance results provided quantitative evidence of FV heads’ significance in ICL. When FV heads were ablated, model accuracy suffered a noticeable decline, with degradation becoming more pronounced in larger models. This impact was significantly greater than the effect of removing induction heads, which showed minimal influence beyond random ablations. Researchers observed that preserving only the top 2% FV heads was sufficient to maintain reasonable ICL performance, whereas ablating them led to a substantial impairment in model accuracy. In contrast, removing induction heads had minimal impact beyond what would be expected from random ablations. This effect was particularly pronounced in larger models, where the role of FV heads became increasingly dominant. Researchers also found that in the Pythia 6.9B model, the accuracy drop when FV heads were removed was substantially greater than when induction heads were ablated, reinforcing the hypothesis that FV heads drive few-shot learning.

These results challenge previous assumptions that induction heads are the primary facilitators of ICL. Instead, the study establishes FV heads as the more crucial component, particularly as models scale in size. The evidence suggests that as models increase in complexity, they rely more heavily on FV heads for effective in-context learning. This insight advances the understanding of ICL mechanisms and provides guidance for optimizing future LLM architectures.

By distinguishing the roles of induction and FV heads, this research shifts the perspective on how LLMs acquire and utilize contextual information. The discovery that FV heads evolve from induction heads highlights an important developmental process within these models. Future studies may explore ways to enhance FV head formation, improving the efficiency and adaptability of LLMs. The findings also have implications for model interpretability, as understanding these internal mechanisms can aid in developing more transparent and controllable AI systems.

Check out the Paper. All credit for this research goes to the researchers of this project. Also, feel free to follow us on Twitter and don’t forget to join our 80k+ ML SubReddit.

Recommended Read- LG AI Research Releases NEXUS: An Advanced System Integrating Agent AI System and Data Compliance Standards to Address Legal Concerns in AI Datasets
The post This AI Paper Identifies Function Vector Heads as Key Drivers of In-Context Learning in Large Language Models appeared first on MarkTechPost.

Accelerate AWS Well-Architected reviews with Generative AI

Building cloud infrastructure based on proven best practices promotes security, reliability and cost efficiency. To achieve these goals, the AWS Well-Architected Framework provides comprehensive guidance for building and improving cloud architectures. As systems scale, conducting thorough AWS Well-Architected Framework Reviews (WAFRs) becomes even more crucial, offering deeper insights and strategic value to help organizations optimize their growing cloud environments.
In this post, we explore a generative AI solution leveraging Amazon Bedrock to streamline the WAFR process. We demonstrate how to harness the power of LLMs to build an intelligent, scalable system that analyzes architecture documents and generates insightful recommendations based on AWS Well-Architected best practices. This solution automates portions of the WAFR report creation, helping solutions architects improve the efficiency and thoroughness of architectural assessments while supporting their decision-making process.
Scaling Well-Architected reviews using a generative AI-powered solution
As organizations expand their cloud footprint, they face several challenges in adhering to the Well-Architected Framework:

Time-consuming and resource-intensive manual reviews
Inconsistent application of Well-Architected principles across different teams
Difficulty in keeping pace with the latest best practices
Challenges in scaling reviews for large or numerous architectures

To address these challenges, we have built a WAFR Accelerator solution that uses generative AI to help streamline and expedite the WAFR process. By automating the initial assessment and documentation process, this solution significantly reduces time spent on evaluations while providing consistent architecture assessments against AWS Well-Architected principles. This allows teams to focus more on implementing improvements and optimizing AWS infrastructure. The solution incorporates the following key features:

Using a Retrieval Augmented Generation (RAG) architecture, the system generates a context-aware detailed assessment. The assessment includes a solution summary, an evaluation against Well-Architected pillars, an analysis of adherence to best practices, actionable improvement recommendations, and a risk assessment.
 An interactive chat interface allows deeper exploration of both the original document and generated content.
Integration with the AWS Well-Architected Tool pre-populates workload information and initial assessment responses.

This solution offers the following key benefits:

Rapid analysis and resource optimization – What previously took days of manual review can now be accomplished in minutes, allowing for faster iteration and improvement of architectures. This time efficiency translates to significant cost savings and optimized resource allocation in the review process.
Consistency and enhanced accuracy – The approach provides a consistent application of AWS Well-Architected principles across reviews, reducing human bias and oversight. This systematic approach leads to more reliable and standardized evaluations.
Depth of insight – Advanced analysis can identify subtle patterns and potential issues that might be missed in manual reviews, providing deeper insights into architectural strengths and weaknesses.
Scalability – The solution can handle multiple reviews simultaneously, making it suitable for organizations of all sizes, from startups to enterprises. This scalability allows for more frequent and comprehensive reviews.
Interactive exploration -The generative AI-driven chat interface allows users to dive deeper into the assessment, asking follow-up questions and gaining a better understanding of the recommendations. This interactivity enhances engagement and promotes more thorough comprehension of the results.

Solution overview
The WAFR Accelerator is designed to streamline and enhance the architecture review process by using the capabilities of generative AI through Amazon Bedrock and other AWS services. This solution automates the analysis of complex architecture documents, evaluating them against the AWS Well-Architected Framework’s pillars and providing detailed assessments and recommendations.
The solution consists of the following capabilties:

Generative AI-powered analysis – Uses Amazon Bedrock to rapidly analyze architecture documents against AWS Well-Architected best practices, generating detailed assessments and recommendations.
Knowledge base integration – Incorporates up-to-date WAFR documentation and cloud best practices using Amazon Bedrock Knowledge Bases, providing accurate and context-aware evaluations.
Customizable – Uses prompt engineering, which enables customization and iterative refinement of the prompts used to drive the large language model (LLM), allowing for refining and continuous enhancement of the assessment process.
Integration with the AWS Well-Architected Tool – Creates a Well-Architected workload milestone for the assessment and prepopulates answers for WAFR questions based on generative AI-based assessment.
Generative AI-assisted chat – Offers an AI-driven chat interface for in-depth exploration of assessment results, supporting multi-turn conversations with context management.
Scalable architecture – Uses AWS services like AWS Lambda and Amazon Simple Queue Service (Amazon SQS) for efficient processing of multiple reviews.
Data privacy and network security – With Amazon Bedrock, you are in control of your data, and all your inputs and customizations remain private to your AWS account. Your data, such as prompts, completions, custom models, and data used for fine-tuning or continued pre-training, is not used for service improvement and is never shared with third-party model providers. Your data remains in the AWS Region where the API call is processed. All data is encrypted in transit and at rest. You can use AWS PrivateLink to create a private connection between your VPC and Amazon Bedrock.

A human-in-the-loop review is still crucial to validate the generative AI findings, checking for accuracy and alignment with organizational requirements.
The following diagram illustrates the solution’s technical architecture.

The workflow consists of the following steps:

WAFR guidance documents are uploaded to a bucket in Amazon Simple Storage Service (Amazon S3). These documents form the foundation of the RAG architecture. Using Amazon Bedrock Knowledge Base, the sample solution ingests these documents and generates embeddings, which are then stored and indexed in Amazon OpenSearch Serverless. This creates a vector database that enables retrieval of relevant WAFR guidance during the review process
Users access the WAFR Accelerator Streamlit application through Amazon CloudFront, which provides secure and scalable content delivery. User authentication is handled by Amazon Cognito, making sure only authenticated user have access.
Users upload their solution architecture document in PDF format using the Streamlit application running on an Amazon Elastic Compute Cloud (Amazon EC2) instance that stores it in an S3 bucket. On submission, the WAFR review process is invoked by Amazon SQS, which queues the review request.
The WAFR reviewer, based on Lambda and AWS Step Functions, is activated by Amazon SQS. It orchestrates the review process, including document content extraction, prompt generation, solution summary, knowledge embedding retrieval, and generation.
Amazon Textract extracts the content from the uploaded documents, making it machine-readable for further processing.
The WAFR reviewer uses Amazon Bedrock Knowledge Bases’ fully managed RAG workflow to query the vector database in OpenSearch Serverless, retrieving relevant WAFR guidance based on the selected WAFR pillar and questions. Metadata filtering is used to improve retrieval accuracy.
Using the extracted document content and retrieved embeddings, the WAFR reviewer generates an assessment using Amazon Bedrock. A workload is created in the AWS Well-Architected Tool with answers populated with the assessment results. This allows users to download initial version of the AWS Well-Architected report from the AWS Well-Architected Tool console on completion of the assessment.
The assessment is also stored in an Amazon DynamoDB table for quick retrieval and future reference.
The WAFR Accelerator application retrieves the review status from the DynamoDB table to keep the user informed.
Users can chat with the content using Amazon Bedrock, allowing for deeper exploration of the document, assessment, and recommendations.
Once the assessment is complete, human reviewers can review it in the AWS Well-Architected Tool.

Deploy the solution
To implement the solution in your own environment, we’ve provided resources in the following GitHub repo to guide you through the process. The setup is streamlined using the AWS Cloud Development Kit (AWS CDK), which allows for infrastructure as code (IaC) deployment. For step-by-step instructions, we’ve prepared a detailed README file that walks you through the entire setup process.
To get started, complete the following steps:

Clone the provided repository containing the AWS CDK code and README file.
Review the README file for prerequisites and environment setup instructions.
Follow the AWS CDK deployment steps outlined in the documentation.
Configure necessary environment-specific parameters as described.

Deploying and running this solution in your AWS environment will incur costs for the AWS services used, including but not limited to Amazon Bedrock, Amazon EC2, Amazon S3, and DynamoDB. It is highly recommended that you use a separate AWS account and setup AWS Budget to monitor the costs.

DISCLAIMER: This is sample code for non-production usage. You should work with your security and legal teams to adhere to your organizational security, regulatory, and compliance requirements before deployment.

Test the solution
The following diagram illustrates the workflow for using the application.

To demonstrate how generative AI can accelerate AWS Well-Architected reviews, we have developed a Streamlit-based demo web application that serves as the front-end interface for initiating and managing the WAFR review process.
Complete the following steps to test the demo application:

Open a new browser window and enter the CloudFront URL provided during the setup.
Add a new user to the Amazon Cognito user pool deployed by the AWS CDK during the setup. Log in to the application using this user’s credentials.
Choose New WAFR Review in the navigation pane.
For Analysis type, choose the analysis type:

Quick – You can generate a quick analysis without creating a workload in the AWS Well-Architected Tool. This option is faster because it groups the questions for an individual pillar into a single prompt. It’s suitable for an initial assessment.
Deep with Well-Architected Tool – You can generate a comprehensive and detailed analysis that automatically creates a workload in the AWS Well-Architected tool. This thorough review process requires more time to complete as it evaluates each question individually rather than grouping them together. The deep review typically takes approximately 20 minutes, though the actual duration may vary depending on the document size and the number of Well- Architected pillars selected for evaluation.

Enter the analysis name and description.
Choose the AWS Well-Architected lens and desired pillars.
Upload your solution architecture or technical design document
Choose Create WAFR Analysis.
Choose Existing WAFR Reviews in the navigation pane.
Choose your newly submitted analysis.

After the status changes to Completed, you can view the WAFR analysis at the bottom of the page. For multiple reviews, choose the relevant analysis on the dropdown menu.

You can chat with the uploaded document as well as the other generated content by using the WAFR Chat section on the Existing WAFR Reviews page.

Improving assessment quality
The solution uses prompt engineering to optimize textual input to the foundation model (FM) to obtain desired assessment responses. The quality of prompt (the system prompt, in this case) has significant impact on the model output. The solution provides a sample system prompt that is used to drive the assessment. You could enhance this prompt further to align with specific organizational needs. This becomes more crucial when defining and ingesting your own custom lenses.
Another important factor is the quality of the document that is uploaded for assessment. Detailed and architecture-rich documents can result in better inferences and therefore finer assessments. Prompts are defined in such a way that if there is inadequate information for assessment, then it’s highlighted in the output. This minimizes hallucination by the FM and provides a potential opportunity to enrich your design templates in alignment with AWS Well-Architected content.
You could further enhance this solution by using Amazon Bedrock Guardrails to further reduce hallucinations and ground responses in your own source information.
At the time of writing of this blog, only the AWS Well-Architected Framework, Financial Services Industry, and Analytics lenses have been provisioned. However, other lenses, including custom lenses, could be added with a few refinements to the UI application and underlying data store.
Clean up
After you’ve finished exploring or using the solution and no longer require these resources, be sure to clean them up to avoid ongoing charges. Follow these steps to remove all associated resources:

Navigate to the directory containing your AWS CDK code.
Run the following command: cdk destroy.
Confirm the deletion when prompted.
Manually check for and delete any resources that might not have been automatically removed, such as S3 buckets with content or custom IAM roles.
Verify that all related resources have been successfully deleted.

Conclusion
In this post, we showed how generative AI and Amazon Bedrock can play a crucial role in expediting and scaling the AWS Well-Architected Framework reviews within an organization. By automating document analysis and using a WAFR-aware knowledge base, the solution offers rapid and in-depth assessments, helping organizations build secure, high-performing, resilient, and efficient infrastructure for a variety of applications and workloads.
To learn more, refer to the following:

Amazon Bedrock Documentation
AWS Well-Architected
Amazon Bedrock Knowledge Bases now supports metadata filtering to improve retrieval accuracy

About the Authors
Shoeb Bustani is a Senior Enterprise Solutions Architect at AWS, based in the United Kingdom. As a senior enterprise architect, innovator, and public speaker, he provides strategic architectural partnership and guidance to help customers achieve their business outcome leveraging AWS services and best practices.
Brijesh Pati is an Enterprise Solutions Architect at AWS, helping enterprise customers adopt cloud technologies. With a background in application development and enterprise architecture, he has worked with customers across sports, finance, energy, and professional services sectors. Brijesh specializes in AI/ML solutions and has experience with serverless architectures.
Rohan Ghosh is as an Enterprise Solutions Architect at Amazon Web Services (AWS), specializing in the Advertising and Marketing sector. With extensive experience in Cloud Solutions Engineering, Application Development, and Enterprise Support, he helps organizations architect and implement cutting-edge cloud solutions. His current focus areas include Data Analytics and Generative AI, where he guides customers in leveraging AWS technologies to drive innovation and business transformation.

Dynamic metadata filtering for Amazon Bedrock Knowledge Bases with Lan …

Amazon Bedrock Knowledge Bases offers a fully managed Retrieval Augmented Generation (RAG) feature that connects large language models (LLMs) to internal data sources. It’s a cost-effective approach to improving LLM output so it remains relevant, accurate, and useful in various contexts. It also provides developers with greater control over the LLM’s outputs, including the ability to include citations and manage sensitive information.
Amazon Bedrock Knowledge Bases has a metadata filtering capability that allows you to refine search results based on specific attributes of the documents, improving retrieval accuracy and the relevance of responses. These metadata filters can be used in combination with the typical semantic (or hybrid) similarity search. Improving document retrieval results helps personalize the responses generated for each user. Dynamic metadata filters allow you to instantly create custom queries based on the varying user profiles or user-inputted responses so the documents retrieved only contain information relevant to the your needs.
In this post, we discuss using metadata filters with Amazon Bedrock Knowledge Bases.
Solution overview
The following code is an example metadata filter for Amazon Bedrock Knowledge Bases. Logical operators (such as AND or OR) can be nested to combine other logical operators and filter conditions. For more information, refer to the Retrieve API.

{
“andAll”: [
{
“equals”: {
“key”: “desired_destination”,
“value”: “<UNKNOWN>” # This will be overwritten with appropriate values at runtime
}
},
{
“equals”: {
“key”: “travelling_with_children”,
“value”: “<UNKNOWN>” # This will be overwritten with appropriate values at runtime
}
}
]
}

For our use case, we use an example of a travel website where the user answers a few questions about their travel preferences (including desired destination, preferred activities, and traveling companions) and then the system retrieves relevant documents.
We exclusively focus on the retrieval portion of RAG in this post. We provide the upstream components, including document ingestion and query formatting, as static data instead of code. The downstream generation component is out of scope for this post.
Prerequisites
To follow along with this post, you should understand basic retrieval techniques such as similarity search.
Additionally, you need an Amazon Bedrock knowledge base populated with documents and metadata. For instructions, see Create an Amazon Bedrock knowledge base. We have provided example documents and metadata in the accompanying GitHub repo for you to upload.
The associated notebook contains the required library imports and environment variables. Make sure you run the notebook using an AWS Identity and Access Management (IAM) role with the correct permissions for Amazon Simple Storage Service (Amazon S3) and Amazon Bedrock (AmazonS3FullAccess and AmazonBedrockFullAccess, respectively). We recommend running the notebook locally or in Amazon SageMaker. Then you can run the following code to test your AWS and knowledge base connection:

# Test AWS connection
# Create a session using your AWS credentials
session = boto3.Session()

# Create an STS client
sts_client = session.client(‘sts’)

# Get the caller identity
response = sts_client.get_caller_identity()

# Print the response
print(response)

knowledge_base_id = ‘XXXXXXXXXX’

retrieval_config = {
“vectorSearchConfiguration”: {
“numberOfResults”: 4,
“overrideSearchType”: “HYBRID”
}
}

# Test bedrock knowledge bases connection
client = boto3.client(‘bedrock-agent-runtime’)

response = client.retrieve(
knowledgeBaseId=knowledge_base_id,
retrievalConfiguration=retrieval_config,
retrievalQuery={“text”: “Hello world”}
)

print(response)

Create a dynamic filter
The “value” field within the filter needs to be updated at request time. This means overwriting the retrieval_config object, as shown in the following figure. The placeholder values in the filter get overwritten with the user data at runtime.

Because the retrieval_config object is a nested hierarchy of logical conditions (a tree), you can implement a breadth first search to identify and replace all the “value” field values (where “value” is the key and “<UNKNOWN>” is the placeholder value) with the corresponding value from the user data. See the following code:

def setup_retrieval_config(inputs):

# Make a copy because the filter is updated dynamically based on the user_data, this allows you to start from the default each time
local_retrieval_config = copy.deepcopy(retrieval_config)

updated_vector_search_config = replace_values(local_retrieval_config[“vectorSearchConfiguration”], inputs[“user_data”])
local_retrieval_config[“vectorSearchConfiguration”] = updated_vector_search_config

return local_retrieval_config

def replace_values(vector_search_config: Dict, user_data: Dict):
# Replace the value fields in the filter with the correct value according to the user_data
# Uses breadth first search to find all of the value fields

# Filter is not a required key, if you do not want any filters get rid of the key
if “filter” in vector_search_config and not vector_search_config[“filter”]:
del vector_search_config[“filter”]

# Recursively traverse from the root
elif ‘filter’ in vector_search_config:
vector_search_config[‘filter’] = replace_values(vector_search_config[‘filter’], user_data)

# At a node that is not the root
else:
for key, value in vector_search_config.items():
if isinstance(value, dict):

# At a leaf e.g. {“key”: “age”, “value”: “”}}
if ‘key’ in value and ‘value’ in value:

# Only overwrite value[‘value’] that are not unknown
if value[‘key’] in user_data and not (value[“value”] == “unknown” or value[“value”] == [“unknown”]):

# Primitive data type
if type(value[“value”]) in [str, int, float, bool]:
value[‘value’] = user_data[value[‘key’]]

# List data type
elif isinstance(value[“value”], list):
value[‘value’] = [user_data[value[‘key’]]]
else:
raise ValueError(f”Unsupported value[‘value’] type {type(value[‘value’])}”)
else:
vector_search_config[key] = replace_values(value, user_data)

# Recurse on each item in the list
elif isinstance(value, list):
vector_search_config[key] = [replace_values(item, user_data) for item in value]
else:
raise ValueError(f”Unsupported value type {type(value)}”)

return vector_search_config

Option 1: Create a retriever each time
To define the retrieval_config parameter dynamically, you can instantiate AmazonKnowledgeBasesRetriever each time. This integrates into a larger LangChain centric code base. See the following code:

def create_retrieval_chain() -> Runnable:
“””
Creates a retrieval chain for the retriever.

Returns:
Runnable: The retrieval chain.
“””

query = create_query_for_retrieval()

def create_retriever(inputs):
# This wrapper is necessary because if you return a callable object LangChain will automatically call it immediately, which is not the desired behavior
# instead we want to call the retriever on the next step of the chain
retriever_wrapper = {“retriever”: AmazonKnowledgeBasesRetriever(knowledge_base_id=knowledge_base_id, retrieval_config=inputs[“retrieval_config”])}
return retriever_wrapper

# Retrieval chain has three steps: (1) create the filter based off of the user data, (2) create the retriever, and (3) invoke the retriever
retrieval_chain = (
{
“user_data” : itemgetter(“user_data”),
“retrieval_config” : lambda inputs: setup_retrieval_config(inputs)
} |
{
“query” : query,
“retriever” : lambda inputs: create_retriever(inputs)
} |
RunnableLambda(lambda inputs: inputs[“retriever”][“retriever”].invoke(inputs[“query”]))
)
return retrieval_chain

Option 2: Access the underlying Boto3 API
The Boto3 API is able to directly retrieve with a dynamic retrieval_config. You can take advantage of this by accessing the object that AmazonKnowledgeBasesRetriever wraps. This is slightly faster but is less pythonic because it relies on LangChain implementation details, which may change without notice. This requires additional code to adapt the output to the proper format for a LangChain retriever. See the following code:

retriever = AmazonKnowledgeBasesRetriever(
knowledge_base_id=knowledge_base_id,
retrieval_config=retrieval_config
)

def create_retrieval_chain() -> Runnable:
“””
Creates a retrieval chain for the retriever.

Returns:
Runnable: The retrieval chain.
“””

query = create_query_for_retrieval()

def retrieve_and_format(inputs):
results = retriever.client.retrieve(
retrievalQuery={“text”: inputs[“query”]},
knowledgeBaseId=knowledge_base_id,
retrievalConfiguration=inputs[“retrieval_config”]
)

documents = []
for result in results[“retrievalResults”]:
metadata = {
“location”: result[“location”],
“source_metadata”: result[“metadata”],
“score”: result[“score”],
}

document = Document(
page_content=result[“content”][“text”],
metadata=metadata
)
documents.append(document)

return documents

retrieval_chain = (
{
“query” : query,
“retrieval_config” : lambda inputs: setup_retrieval_config(inputs)
} |
RunnableLambda(lambda inputs: retrieve_and_format(inputs))
# RunnableLambda(lambda inputs: retriever.client.retrieve(retrievalQuery={“text”: inputs[“query”]}, knowledgeBaseId=knowledge_base_id, retrievalConfiguration=inputs[“retrieval_config”]))
)
return retrieval_chain

retrieval_chain_2 = create_retrieval_chain()

Results
Begin by reading in the user data. This example data contains user answers to an online questionnaire about travel preferences. The user_data fields must match the metadata fields.

with open(“data/user_data.json”, “r”) as file:
user_data = json.load(file)

print(json.dumps(user_data[:2], indent=2))

Here is a preview of the user_data.json file from which certain fields will be extracted as values for filters.

{
“trip_id”: 1,
“desired_destination”: “Bali, Indonesia”,
“stay_duration”: 7,
“age”: 35,
“gender”: “male”,
“companion”: “solo”,
“travelling_with_children”: “no”,
“travelling_with_pets”: “no”
},
{
“trip_id”: 2,
“desired_destination”: “Paris, France”,
“stay_duration”: 5,
“age”: 28,
“gender”: “female”,
“companion”: “solo”,
“travelling_with_children”: “no”,
“travelling_with_pets”: “yes”
},

Test the code with filters turned on and off. Only use a few filtering criteria because restrictive filters might return zero documents.

filters_to_test: List = [
{
“andAll”: [
{
“equals”: {
“key”: “desired_destination”,
“value”: “<UNKNOWN>” # This will be overwritten with appropriate values at runtime
}
},
{
“equals”: {
“key”: “travelling_with_children”,
“value”: “<UNKNOWN>” # This will be overwritten with appropriate values at runtime
}
}
]
},
None
]

Finally, run both retrieval chains through both sets of filters for each user:

retrieval_chains = [retrieval_chain_1, retrieval_chain_2]

results = []

for retrieval_chain_id, retrieval_chain in enumerate(retrieval_chains):
logger.info(retrieval_chain_id)
# Loop through each filter options
for filter in filters_to_test:
retrieval_config[“vectorSearchConfiguration”][“filter”] = filter
# Loop through each user data entry
for user_entry in user_data:
inputs = {
“user_data”: user_entry,
“retrieval_config”: retrieval_config
}

# Run the retrieval chain with the current user entry
try:
result = retrieval_chain.invoke(inputs)
# print(f”Result for user entry {user_entry[‘trip_id’]}: {result}”)
results.append(({‘retrieval_chain_id’: retrieval_chain_id, ‘user’: user_entry, ‘documents’: result}))

except Exception as e:
print(f”Error during retrieval for user entry {user_entry[‘trip_id’]}: {e}”)

When analyzing the results, you can see that the first half of the documents are identical to the second half. In addition, when metadata filters aren’t used, the documents retrieved are occasionally for the wrong location. For example, trip ID 2 is to Paris, but the retriever pulls documents about London.
Excerpt of output table for reference:

Retrieval Approach
Filter
Trip ID
Destination
Page Content
Metadata

Option_0
TRUE
2
Paris, France
As a 70-year-old retiree, I recently had the pleasure of visiting Paris for the first time. It was a trip I had been looking forward to for years, and I was not disappointed. Here are some of my favorite attractions and activities that I would recommend to other seniors visiting the city.  First on my list is the Eiffel Tower…
{‘location’: {‘s3Location’: {‘uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/Paris_6.txt‘}, ‘type’: ‘S3’}, ‘score’: 0.48863396, ‘source_metadata’: {‘x-amz-bedrock-kb-source-uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/Paris_6.txt‘, ‘travelling_with_children’: ‘no’, ‘activities_interest’: [‘museums’, ‘palaces’, ‘strolling’, ‘boat tours’, ‘neighborhood tours’], ‘companion’: ‘unknown’, ‘x-amz-bedrock-kb-data-source-id’: {YOUR_KNOWLEDGE_BASE_ID}, ‘stay_duration’: ‘unknown’, ‘preferred_month’: [‘unknown’], ‘travelling_with_pets’: ‘unknown’, ‘age’: [’71’, ’80’], ‘x-amz-bedrock-kb-chunk-id’: ‘1%3A0%3AiNKlapMBdxcT3sYpRK-d’, ‘desired_destination’: ‘Paris, France’}}

Option_0
TRUE
2
Paris, France
As a 35-year-old traveling with my two dogs, I found Paris to be a pet-friendly city with plenty of attractions and activities for pet owners. Here are some of my top recommendations for traveling with pets in Paris:  The Jardin des Tuileries is a beautiful park located between the Louvre Museum and the Place de la Concorde…
{‘location’: {‘s3Location’: {‘uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/Paris_9.txt‘}, ‘type’: ‘S3’}, ‘score’: 0.474106, ‘source_metadata’: {‘x-amz-bedrock-kb-source-uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/Paris_9.txt‘, ‘travelling_with_children’: ‘no’, ‘activities_interest’: [‘parks’, ‘museums’, ‘river cruises’, ‘neighborhood exploration’], ‘companion’: ‘pets’, ‘x-amz-bedrock-kb-data-source-id’: {YOUR_KNOWLEDGE_BASE_ID}, ‘stay_duration’: ‘unknown’, ‘preferred_month’: [‘unknown’], ‘travelling_with_pets’: ‘yes’, ‘age’: [’30’, ’31’, ’32’, ’33’, ’34’, ’35’, ’36’, ’37’, ’38’, ’39’, ’40’], ‘x-amz-bedrock-kb-chunk-id’: ‘1%3A0%3Aj52lapMBuHB13c7-hl-4’, ‘desired_destination’: ‘Paris, France’}}

Option_0
TRUE
2
Paris, France
If you are looking for something a little more active, I would suggest visiting the Bois de Boulogne. This large park is located on the western edge of Paris and is a great place to go for a walk or a bike ride with your pet. The park has several lakes and ponds, as well as several gardens and playgrounds…
{‘location’: {‘s3Location’: {‘uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/Paris_5.txt‘}, ‘type’: ‘S3’}, ‘score’: 0.45283788, ‘source_metadata’: {‘x-amz-bedrock-kb-source-uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/Paris_5.txt‘, ‘travelling_with_children’: ‘no’, ‘activities_interest’: [‘strolling’, ‘picnic’, ‘walk or bike ride’, ‘cafes and restaurants’, ‘art galleries and shops’], ‘companion’: ‘pet’, ‘x-amz-bedrock-kb-data-source-id’: ‘{YOUR_KNOWLEDGE_BASE_ID}, ‘stay_duration’: ‘unknown’, ‘preferred_month’: [‘unknown’], ‘travelling_with_pets’: ‘yes’, ‘age’: [’40’, ’41’, ’42’, ’43’, ’44’, ’45’, ’46’, ’47’, ’48’, ’49’, ’50’], ‘x-amz-bedrock-kb-chunk-id’: ‘1%3A0%3AmtKlapMBdxcT3sYpSK_N’, ‘desired_destination’: ‘Paris, France’}}

Option_0
FALSE
2
Paris, France
{   “metadataAttributes”: {     “age”: [       “30”     ],     “desired_destination”: “London, United Kingdom”,     “stay_duration”: “unknown”,     “preferred_month”: [       “unknown”     ],     “activities_interest”: [       “strolling”,       “sightseeing”,       “boating”,       “eating out”     ],     “companion”: “pets”,     “travelling_with_children”: “no”,     “travelling_with_pets”: “yes”   } }
{‘location’: {‘s3Location’: {‘uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/London_2.txt.metadata (1).json’}, ‘type’: ‘S3’}, ‘score’: 0.49567315, ‘source_metadata’: {‘x-amz-bedrock-kb-source-uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/London_2.txt.metadata (1).json’, ‘x-amz-bedrock-kb-chunk-id’: ‘1%3A0%3A5tKlapMBdxcT3sYpYq_r’, ‘x-amz-bedrock-kb-data-source-id’: {YOUR_KNOWLEDGE_BASE_ID}}}

Option_0
FALSE
2
Paris, France
As a 35-year-old traveling with my two dogs, I found Paris to be a pet-friendly city with plenty of attractions and activities for pet owners. Here are some of my top recommendations for traveling with pets in Paris:  The Jardin des Tuileries is a beautiful park located between the Louvre Museum and the Place de la Concorde…
{‘location’: {‘s3Location’: {‘uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/Paris_9.txt‘}, ‘type’: ‘S3’}, ‘score’: 0.4741059, ‘source_metadata’: {‘x-amz-bedrock-kb-source-uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/Paris_9.txt‘, ‘travelling_with_children’: ‘no’, ‘activities_interest’: [‘parks’, ‘museums’, ‘river cruises’, ‘neighborhood exploration’], ‘companion’: ‘pets’, ‘x-amz-bedrock-kb-data-source-id’: {YOUR_KNOWLEDGE_BASE_ID}, ‘stay_duration’: ‘unknown’, ‘preferred_month’: [‘unknown’], ‘travelling_with_pets’: ‘yes’, ‘age’: [’30’, ’31’, ’32’, ’33’, ’34’, ’35’, ’36’, ’37’, ’38’, ’39’, ’40’], ‘x-amz-bedrock-kb-chunk-id’: ‘1%3A0%3Aj52lapMBuHB13c7-hl-4’, ‘desired_destination’: ‘Paris, France’}}

Option_0
FALSE
2
Paris, France
If you are looking for something a little more active, I would suggest visiting the Bois de Boulogne. This large park is located on the western edge of Paris and is a great place to go for a walk or a bike ride with your pet. The park has several lakes and ponds, as well as several gardens and playgrounds…
{‘location’: {‘s3Location’: {‘uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/Paris_5.txt‘}, ‘type’: ‘S3’}, ‘score’: 0.45283788, ‘source_metadata’: {‘x-amz-bedrock-kb-source-uri’: ‘s3://{YOUR_S3_BUCKET}/travel_reviews_titan/Paris_5.txt‘, ‘travelling_with_children’: ‘no’, ‘activities_interest’: [‘strolling’, ‘picnic’, ‘walk or bike ride’, ‘cafes and restaurants’, ‘art galleries and shops’], ‘companion’: ‘pet’, ‘x-amz-bedrock-kb-data-source-id’: {YOUR_KNOWLEDGE_BASE_ID}, ‘stay_duration’: ‘unknown’, ‘preferred_month’: [‘unknown’], ‘travelling_with_pets’: ‘yes’, ‘age’: [’40’, ’41’, ’42’, ’43’, ’44’, ’45’, ’46’, ’47’, ’48’, ’49’, ’50’], ‘x-amz-bedrock-kb-chunk-id’: ‘1%3A0%3AmtKlapMBdxcT3sYpSK_N’, ‘desired_destination’: ‘Paris, France’}}

Clean up
To avoid incurring additional charges, be sure to delete your knowledge base, OSS/vector store and the underlying S3 bucket.
Conclusion
Enabling dynamic filtering through Knowledge Base’s metadata filtering enhances document retrieval in RAG systems by tailoring outputs to user-specific needs, significantly improving the relevance and accuracy of LLM-generated responses. In the travel website example, filters make sure that retrieved documents closely matched user preferences.
This approach can be applied to other use cases, such as customer support, personalized recommendations, and content curation, where context-sensitive information retrieval is essential. Properly configured filters are crucial for maintaining accuracy across different applications, making this feature a powerful tool for refining LLM outputs in diverse scenarios.
Be sure to take advantage of this powerful and flexible solution in your application. For more information on metadata in Amazon Bedrock Knowledge Bases, see Amazon Bedrock Knowledge Bases now supports metadata filtering to improve retrieval accuracy. Also, Amazon Bedrock Knowledge Bases now provides autogenerated query filters.
Security Best Practices
For AWS IAM Policies:

Apply least-privilege permissions by being explicit with IAM actions and listing only required permissions rather than using wildcards
Use temporary credentials with IAM roles for workloads
Avoid using wildcards (*) in the Action element as this grants access to all actions for specific AWS services
Remove wildcards from the Resource element and explicitly list the specific resources that IAM entities should access
Review AWS managed policies carefully before using them and consider using customer managed policies if AWS managed policies grant more permissions than needed

For more detailed security best practices for AWS IAM, see Security best practices in IAM.
For Amazon S3:

Block Public Access unless explicitly required, make sure S3 buckets are not publicly accessible by using the S3 Block Public Access feature and implementing appropriate bucket policies
Enable encryption for data at rest (all S3 buckets have default encryption) and enforce encryption for data in transit using HTTPS/TLS
Grant only the minimum permissions required using IAM policies, bucket policies, and disable ACLs (Access Control Lists) which are no longer recommended for most modern use cases
Enable server access logging, AWS CloudTrail, and use AWS security services like GuardDuty, Macie, and IAM Access Analyzer to monitor and detect potential security issues

For more detailed security best practices for Amazon S3, see Security best practices for Amazon S3.
For Amazon Bedrock:

Use IAM roles and policies to control access to Bedrock resources and APIs.
Implement VPC endpoints to access Bedrock securely from within your VPC.
Encrypt data at rest and in transit when working with Bedrock to protect sensitive information.
Monitor Bedrock usage and access patterns using AWS CloudTrail for auditing purposes.

For more information on security in Amazon Bedrock, see Security in Amazon Bedrock.
For Amazon SageMaker:

Use IAM roles to control access to SageMaker resources and limit permissions based on job functions.
Encrypt SageMaker notebooks, training jobs, and endpoints using AWS KMS keys for data protection.
Implement VPC configurations for SageMaker resources to restrict network access and enhance security.
Use SageMaker private endpoints to access APIs without traversing the public internet.

About the Authors
Haley Tien is a Deep Learning Architect at AWS Generative AI Innovation Center. She has a Master’s degree in Data Science and assists customers in building generative AI solutions on AWS to optimize their workloads and achieve desired outcomes.
Adam Weinberger is a Applied Scientist II at AWS Generative AI Innovation Center. He has 10 years of experience in data science and machine learning. He holds a Master’s of Information and Data Science from the University of California, Berkeley.
Dan Ford is a Applied Scientist II at AWS Generative AI Innovation Center, where he helps public sector customers build state-of-the-art GenAI solutions.

Customize DeepSeek-R1 distilled models using Amazon SageMaker HyperPod …

Increasingly, organizations across industries are turning to generative AI foundation models (FMs) to enhance their applications. To achieve optimal performance for specific use cases, customers are adopting and adapting these FMs to their unique domain requirements. This need for customization has become even more pronounced with the emergence of new models, such as those released by DeepSeek.
However, customizing DeepSeek models effectively while managing computational resources remains a significant challenge. Tuning model architecture requires technical expertise, training and fine-tuning parameters, and managing distributed training infrastructure, among others. This often forces companies to choose between model performance and practical implementation constraints, creating a critical need for more accessible and streamlined model customization solutions.
In this two-part series, we discuss how you can reduce the DeepSeek model customization complexity by using the pre-built fine-tuning workflows (also called “recipes”) for both DeepSeek-R1 model and its distilled variations, released as part of Amazon SageMaker HyperPod recipes.
In this first post, we will build a solution architecture for fine-tuning DeepSeek-R1 distilled models and demonstrate the approach by providing a step-by-step example on customizing the DeepSeek-R1 Distill Qwen 7b model using recipes, achieving an average of 25% on all the Rouge scores, with a maximum of 49% on Rouge 2 score with both SageMaker HyperPod and SageMaker training jobs. The second part of the series will focus on fine-tuning the DeepSeek-R1 671b model itself.
At the time of this writing, the DeepSeek-R1 model and its distilled variations for Llama and Qwen were the latest released recipe. Check out sagemaker-hyperpod-recipes on GitHub for the latest released recipes, including support for fine-tuning the DeepSeek-R1 671b parameter model.
Amazon SageMaker HyperPod recipes
At re:Invent 2024, we announced the general availability of Amazon SageMaker HyperPod recipes. SageMaker HyperPod recipes help data scientists and developers of all skill sets to get started training and fine-tuning popular publicly available generative AI models in minutes with state-of-the-art training performance. These recipes include a training stack validated by Amazon Web Services (AWS), which removes the tedious work of experimenting with different model configurations, minimizing the time it takes for iterative evaluation and testing. They automate several critical steps, such as loading training datasets, applying distributed training techniques, automating checkpoints for faster recovery from faults, and managing the end-to-end training loop.
Recipes, paired with the resilient infrastructure of AWS, (Amazon SageMaker HyperPod and Amazon SageMaker Model Training) provide a resilient training environment for fine-tuning FMs such as DeepSeek-R1 with out-of-the-box customization.
To help customers quickly use DeepSeek’s powerful and cost-efficient models to accelerate generative AI innovation, we released new recipes to fine-tune six DeepSeek models, including DeepSeek-R1 distilled Llama and Qwen models using supervised fine-tuning (SFT), Quantized Low-Rank Adaptation (QLoRA), Low-Rank Adaptation (LoRA) techniques. In this post, we introduce these new recipes and walk you through a solution to fine-tune a DeepSeek Qwen 7b model for an advanced medical reasoning use case.
Solution overview
At its core, as depicted in the following diagram, the recipe architecture implements a hierarchical workflow that begins with a recipe specification that covers a comprehensive configuration defining the training parameters, model architecture, and distributed training strategies. These recipes are processed through the HyperPod recipe launcher, which serves as the orchestration layer responsible for launching a job on the corresponding architecture. The launcher interfaces with underlying cluster management systems such as SageMaker HyperPod (Slurm or Kubernetes) or training jobs, which handle resource allocation and scheduling. It’s a familiar NeMo-style launcher with which you can choose a recipe and run it on your infrastructure of choice (SageMaker HyperPod or training).
For example, after choosing your recipe, you can pre-train or fine-tune a model by running python3 main.py recipes=recipe-name. Alternatively, you can use a launcher script, which is a bash script that is preconfigured to run the chosen training or fine-tuning job on your cluster. You can check out main.py (NeMo style launcher) and launcher scripts for DeepSeek on the GitHub repository hosting SageMaker HyperPod recipes.
A key component of this architecture is the HyperPod training adapter for NeMo, which is built on the NVIDIA NeMo framework and Neuronx Distributed training package, which loads data, creates models, and facilitates efficient data parallelism, model parallelism, and hybrid parallelism strategies, which enables optimal utilization of computational resources across the distributed infrastructure. The architecture’s modular design allows for scalability and flexibility, making it particularly effective for training LLMs that require distributed computing capabilities.

You can run these recipes using SageMaker HyperPod or as SageMaker training jobs. For organizations that require granular control over training infrastructure and extensive customization options, SageMaker HyperPod is the ideal choice. SageMaker training jobs, on the other hand, is tailored for organizations that want a fully managed experience for their training workflows. To learn more details about these service features, refer to Generative AI foundation model training on Amazon SageMaker.
In the next sections, we go over the solution architecture for these services before presenting a step-by-step implementation example for each.
SageMaker HyperPod
To submit jobs using SageMaker HyperPod, you can use the HyperPod recipes launcher, which provides an straightforward mechanism to run recipes on both Slurm and Kubernetes. After you choose your orchestrator, you can choose your recipe’s launcher and have it run on your HyperPod cluster. The launcher will interface with your cluster with Slurm or Kubernetes native constructs. For this post, we use the HyperPod recipes launcher mechanism to run the training on a Slurm cluster. The following image shows the solution architecture for SageMaker HyperPod.

SageMaker training jobs
The workflow for SageMaker training jobs begins with an API request that interfaces with the SageMaker control plane, which manages the orchestration of training resources. The system uses the training jobs launcher to efficiently run workloads on a managed cluster.
The architecture uses Amazon Elastic Container Registry (Amazon ECR) for container image management. Training jobs are executed across a distributed cluster, with seamless integration to multiple storage solutions, including Amazon Simple Storage Service (Amazon S3), Amazon Elastic File Storage (Amazon EFS), and Amazon FSx for Lustre. All of this runs under the SageMaker managed environment, providing optimal resource utilization and security.
This design simplifies the complexity of distributed training while maintaining the flexibility needed for diverse machine learning (ML) workloads, making it an ideal solution for enterprise AI development. The following image shows the solution architecture for SageMaker training jobs.

Solution walkthrough
For this solution, consider a use case for a healthcare industry startup that aims to create an accurate, medically verified chat assistant application that bridges complex medical information with patient-friendly explanations. By fine-tuning DeepSeek-R1 Distill Qwen 7b using the FreedomIntelligence/medical-o1-reasoning-SFT dataset, you can use its medical reasoning capabilities to produce content that maintains clinical accuracy.
Prerequisites
You need to complete the following prerequisites before you can run the DeepSeek-R1 Distill Qwen 7B model fine-tuning notebook.

Make the following quota increase requests for SageMaker. You need to request a minimum of one p4d.24xlarge instance (with 8 x NVIDIA A100 GPUs) ranging to a maximum of two p4d.24xlarge instances (depending on time-to-train and cost-to-train trade-offs for your use case).

On the Service Quotas console, request the following SageMaker quotas:

P4 instances (p4d.24xlarge) for training job usage: 1–2
P4 instances (p4d.24xlarge) for HyperPod clusters (“ml.p4d.24xlarge for cluster usage“): 1-2

If you choose to use HyperPod clusters to run your training, set up a HyperPod Slurm cluster following the documentation at Tutuorial for getting started with SageMaker HyperPod. Alternatively, you can use the AWS CloudFormation template provided in the AWS Workshop Studio at Amazon SageMaker HyperPod Own Account and follow the instructions to set up a cluster and a development environment to access and submit jobs to the cluster.
(Optional) If you choose to use SageMaker training jobs, you can create an Amazon SageMaker Studio domain (refer to Use quick setup for Amazon SageMaker AI) to access Jupyter notebooks with the preceding role. (You can use JupyterLab in your local setup, too.)

Create an AWS Identity and Access Management (IAM) role with managed policies AmazonSageMakerFullAccess and AmazonS3FullAccess to give required access to SageMaker to run the examples.

Clone the GitHub repository with the assets for this deployment. This repository consists of a notebook that references training assets:

git clone https://github.com/aws-samples/sagemaker-distributed-training-workshop.git
cd 18_sagemaker_training_recipes/ft_deepseek_qwen_lora

Next, we run the model_trainer_deepseek_r1_recipe_lora.ipynb notebook to fine-tune the DeepSeek-R1 model using QLoRA on SageMaker.
Prepare the dataset
To prepare the dataset, you need to load the FreedomIntelligence/medical-o1-reasoning-SFT dataset, tokenize and chunk the dataset, and configure the data channels for SageMaker training on Amazon S3. Complete the following steps:

Format the dataset by applying the prompt format for DeepSeek-R1 Distill Qwen 7B:

def generate_prompt(data_point):
    full_prompt = f”””
    Below is an instruction that describes a task, paired with an input that provides further context.
    Write a response that appropriately completes the request.
    Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.

    ### Instruction:
    You are a medical expert with advanced knowledge in clinical reasoning, diagnostics, and treatment planning.
    Please answer the following medical question.

    ### Question:
    {data_point[“Question”]}

    ### Response:
    {data_point[“Complex_CoT”]}

    “””
    return {“prompt”: full_prompt.strip()}

Load the FreedomIntelligence/medical-o1-reasoning-SFT dataset and split it into training and validation datasets:

# Load dataset from the hub
train_set = load_dataset(dataset_name, ‘en’, split=”train[5%:]”)
test_set = load_dataset(dataset_name, ‘en’, split=”train[:5%]”)

train_dataset = train_set.map(
    generate_and_tokenize_prompt,
    remove_columns=columns_to_remove,
    batched=False
)

test_dataset = test_set.map(
    generate_and_tokenize_prompt,
    remove_columns=columns_to_remove,
    batched=False
)

Load the DeepSeek-R1 Distill Qwen 7B tokenizer from the Hugging Face Transformers library and generate tokens for the train and validation datasets:

model_id = “deepseek-ai/DeepSeek-R1-Distill-Qwen-7B”
max_seq_length=1024

# Initialize a tokenizer by loading a pre-trained tokenizer configuration, using the fast tokenizer implementation if available.
tokenizer = AutoTokenizer.from_pretrained(model_id, use_fast=True)

train_dataset = train_dataset.map(tokenize, remove_columns=[“prompt”])
test_dataset = test_dataset.map(tokenize, remove_columns=[“prompt”])

Prepare the training and validation datasets for SageMaker training by saving them as arrow files, which is required by SageMaker HyperPod recipes, and constructing the S3 paths where these files will be uploaded:

train_dataset_s3_path = f”s3://{bucket_name}/{input_path}/train”
val_dataset_s3_path = f”s3://{bucket_name}/{input_path}/test”

train_dataset.save_to_disk(train_dataset_s3_path)
val_dataset.save_to_disk(val_dataset_s3_path)
The dataset above will be used in the examples for both SageMaker training jobs and SageMaker HyerPod.
Option A: Fine-tune using SageMaker training jobs
To fine-tune the model using SageMaker training jobs with recipes, this example uses the ModelTrainer class.
The ModelTrainer class is a newer and more intuitive approach to model training that significantly enhances user experience and supports distributed training, Build Your Own Container (BYOC), and recipes. For additional information about ModelTrainer, you can refer to Accelerate your ML lifecycle using the new and improved Amazon SageMaker Python SDK – Part 1: ModelTrainer
To set up the fine-tuning workload, complete the following steps:

Select the instance type, the container image for the training job, and define the checkpoint path where the model will be stored:

instance_type = “ml.p4d.24xlarge”

image_uri = (
    f”658645717510.dkr.ecr.{sagemaker_session.boto_session.region_name}.amazonaws.com/smdistributed-modelparallel:2.4.1-gpu-py311-cu121″
)

checkpoint_s3_path = f”s3://{bucket_name}/deepseek-r1-distilled-qwen-7b-recipe-lora/checkpoints”

Create the ModelTrainer function to encapsulate the training setup from a selected recipe:

from sagemaker.modules.configs import CheckpointConfig, Compute, InputData, SourceCode, StoppingCondition
from sagemaker.modules.distributed import Torchrun
from sagemaker.modules.train import ModelTrainer

instance_count = 1

# Working override for custom dataset
recipe_overrides = {
    …
    “trainer”: {
        “num_nodes”: instance_count,
        …
    },
    …
    “use_smp_model”: False, # Required for PEFT
    “model”: {
        “hf_model_name_or_path”: model_id,
        “data”: {
            “train_dir”: “/opt/ml/input/data/train”,
            “val_dir”: “/opt/ml/input/data/test”,
        },
    },
}

# Define the compute
compute_configs = Compute(
    instance_type=instance_type,
    instance_count=instance_count,
    keep_alive_period_in_seconds=0
)

model_trainer = ModelTrainer.from_recipe(
    training_image=image_uri,
    training_recipe=”fine-tuning/deepseek/hf_deepseek_r1_distilled_qwen_7b_seq8k_gpu_lora”,
    recipe_overrides=recipe_overrides,
    requirements=”./requirements.txt”,
    compute=compute_configs,
    …
    checkpoint_config=CheckpointConfig(
        s3_uri=f”{checkpoint_s3_path}/{job_prefix}”
    ),
)
You can point to the specific recipe with the training_recipe argument and override the recipe arguments by providing a dictionary as argument of recipe_overrides. In the previous example:

num_nodes: Indicates the number of instances that will be used for the fine-tuning execution
checkpoint_dir: Location in the container where the job will save model checkpoints

The ModelTrainer class simplifies the experience by encapsulating code and training setup directly from the selected recipe. In this example:

training_recipe: hf_deepseek_r1_distilled_qwen_7b_seq8k_gpu_lora is defining fine-tuning setup for the LoRA technique

Set up the input channels for ModelTrainer by creating an InputData objects from the provided S3 bucket paths for the training and test and validation datasets
Submit the training job:

# starting the train job with our uploaded datasets as input
model_trainer.train(input_data_config=data, wait=True)
Option B: Fine-tune using SageMaker HyperPod with Slurm
To fine-tune the model using HyperPod, make sure your cluster is up and ready by following the prerequisites. To access the login or head node of the HyperPod Slurm cluster from your development environment, follow the login instructions at Log in to your cluster in the Amazon SageMaker HyperPod workshop.
Alternatively, you can also use AWS Systems Manager and run a command like the following to start the session. You can find the cluster ID, instance group name, and instance ID on the Amazon SageMaker console.
aws ssm start-session –target sagemaker-cluster:[cluster-id]_[instance-group-name]-[instance-id] –region region_name

In the cluster’s login or head node, run the following commands to set up the environment. Run sudo su – ubuntu to run the remaining commands as the root user unless you have a specific user ID to access the cluster and your POSIX user is created through a lifecycle script on the cluster. Refer to the multi-user setup for more details.

# create a virtual environment 
python3 -m venv ${PWD}/venv
source venv/bin/activate

# clone the recipes repository and set up the environment
git clone –recursive https://github.com/aws/sagemaker-hyperpod-recipes.git
cd sagemaker-hyperpod-recipes
pip3 install -r requirements.txt

Create a squash file using Enroot to run the job on the cluster. Enroot runtime offers GPU acceleration, rootless container support, and seamless integration with high performance computing (HPC) environments, making it ideal for running our workflows securely.

# create a squash file using Enroot
REGION=<region>
IMAGE=”658645717510.dkr.ecr.${REGION}.amazonaws.com/smdistributed-modelparallel:2.4.1-gpu-py311-cu121″
aws ecr get-login-password –region “${REGION}” | docker login –username AWS –password-stdin 658645717510.dkr.ecr.${REGION}.amazonaws.com
enroot import -o $PWD/smdistributed-modelparallel.sqsh dockerd://${IMAGE}

After you’ve created the squash file, update the recipes_collection/config.yaml file with the absolute path to the squash file (created in the preceding step), and update the instance_type if needed. The final config file should have the following parameters:

cluster_type: slurm 

instance_type: p4d.24xlarge

container: /fsx/<path-to-smdistributed-modelparallel>.sqsh

Download the prepared dataset that you uploaded to S3 into the FSx for Lustre volume attached to the cluster. Run the following commands to download the files from Amazon S3:

aws s3 cp s3://{bucket_name}/{input_path}/train /fsx/ubuntu/deepseek/data/train –recursive
aws s3 cp s3://{bucket_name}/{input_path}/test /fsx/ubuntu/deepseek/data/test –recursive

Update the launcher script for fine-tuning the DeepSeek-R1 Distill Qwen 7B model. The launcher scripts serve as convenient wrappers for executing the training script main.py file), which streamlines the process of fine-tuning and parameter adjustment. For fine-tuning the DeepSeek-R1 Qwen 7B model, you can find the specific script at:

launcher_scripts/deepseek/run_hf_deepseek_r1_qwen_7b_seq16k_gpu_fine_tuning.sh

Before running the script, you need to modify the location of the training and validation files and update the HuggingFace model ID and optionally the access token for private models and datasets. The script should look like the following (update recipes.trainer.num_nodes if you’re using a multi-node cluster):

SAGEMAKER_TRAINING_LAUNCHER_DIR=${SAGEMAKER_TRAINING_LAUNCHER_DIR:-“$(pwd)”}

HF_MODEL_NAME_OR_PATH=”deepseek-ai/DeepSeek-R1-Distill-Qwen-7B” # HuggingFace pretrained model name or path
HF_ACCESS_TOKEN=”hf_xxxx” # Optional HuggingFace access token

TRAIN_DIR=”/fsx/ubuntu/deepseek/data/train” # Location of training dataset 
VAL_DIR=”/fsx/ubuntu/deepseek/data/test” # Location of validation dataset

EXP_DIR=”/fsx/ubuntu/deepseek/results” # Location to save experiment info including logging, checkpoints, etc

HYDRA_FULL_ERROR=1 python3 “${SAGEMAKER_TRAINING_LAUNCHER_DIR}/main.py”
    recipes=fine-tuning/deepseek/hf_deepseek_r1_distilled_qwen_7b_seq16k_gpu_fine_tuning
    base_results_dir=”${SAGEMAKER_TRAINING_LAUNCHER_DIR}/results”
    recipes.run.name=”hf-deepseek-r1-distilled-qwen-7b-fine-tuning”
    recipes.exp_manager.exp_dir=”$EXP_DIR”
    recipes.trainer.num_nodes=1
    recipes.model.data.train_dir=”$TRAIN_DIR”
    recipes.model.data.val_dir=”$VAL_DIR”
    recipes.model.hf_model_name_or_path=”$HF_MODEL_NAME_OR_PATH”
    recipes.model.hf_access_token=”$HF_ACCESS_TOKEN”
You can view the recipe for this fine-tuning task under, overriding any additional parameters as needed:
recipes_collection/recipes/fine-tuning/deepseek/hf_deepseek_r1_distilled_qwen_7b_seq16k_gpu_fine_tuning.yaml

Submit the job by running the launcher script:

bash launcher_scripts/deepseek/run_hf_deepseek_r1_qwen_7b_seq16k_gpu_fine_tuning.sh
You can monitor the job using Slurm commands such as squeue and scontrol show to view the status of the job and the corresponding logs. After the job is complete, the trained model will also be available in the results folder, as shown in the following code:
cd results
 ls -R
.:
checkpoints  experiment

./checkpoints:
full

./checkpoints/full:
steps_50

./checkpoints/full/steps_50:
config.json  pytorch_model.bin

./experiment:

Upload the fine-tuned model checkpoint to Amazon S3 for evaluating the model using the validation data:

aws s3 cp /fsx/<path_to_checkpoint> s3://{bucket_name}/{model_prefix}/qwen7b –recursive
Evaluate the fine-tuned model
To objectively evaluate your fine-tuned model, you can run an evaluation job on the validation portion of the dataset.
You can run a SageMaker training job and use ROUGE metrics (ROUGE-1, ROUGE-2, ROUGE-L, and ROUGE-L-Sum), which measure the similarity between machine-generated text and human-written reference text. The SageMaker training job will compute ROUGE metrics for both the base DeepSeek-R1 Distill Qwen 7B model and the fine-tuned one. You can access the code sample for ROUGE evaluation in the sagemaker-distributed-training-workshop on GitHub. Please refer this notebook for details.
Complete the following steps:

Define the S3 path where the fine-tuned checkpoints are stored, the instance_type, and the image uri to use in the training job:

trained_model = <S3_PATH>
instance_type = “ml.p4d.24xlarge”

image_uri = sagemaker.image_uris.retrieve(
    framework=”pytorch”,
    region=sagemaker_session.boto_session.region_name,
    version=”2.4″,
    instance_type=instance_type,
    image_scope=”training”
)
#763104351884.dkr.ecr.us-east-1.amazonaws.com/pytorch-training:2.4-gpu-py311

Create the ModelTrainer function to encapsulate the evaluation script and define the input data:

from sagemaker.modules.configs import Compute, InputData, OutputDataConfig, SourceCode, StoppingCondition
from sagemaker.modules.distributed import Torchrun
from sagemaker.modules.train import ModelTrainer

# Define the script to be run
source_code = SourceCode(
    source_dir=”./scripts”,
    requirements=”requirements.txt”,
    entry_script=”evaluate_recipe.py”,
)

# Define the compute

# Define the ModelTrainer
model_trainer = ModelTrainer(
    training_image=image_uri,
    source_code=source_code,
    compute=compute_configs,
    …
    hyperparameters={
        “model_id”: model_id,  # Hugging Face model id
        “dataset_name”: dataset_name
    }
)

# Pass the input data
train_input = InputData(
channel_name=”adapterdir”,
data_source=trained_model,
)

test_input = InputData(
channel_name=”testdata”,
data_source=test_dataset_s3_path, # S3 path where training data is stored
)

# Check input channels configured
data = [train_input, test_input]

Submit the training job:

# starting the train job with our uploaded datasets as input
model_trainer.train(input_data_config=data, wait=True)
The following table shows the task output for the fine-tuned model and the base model.

Model
Rouge 1
Rouge 2
Rouge L
Rouge L Sum

Base
0.36362
0.08739
0.16345
0.3204

Fine-tuned
0.44232
0.13022
0.17769
0.38989

% Difference
21.64207
49.01703
8.7121
21.68871

Our fine-tuned model demonstrates remarkable efficiency, achieving about 22% overall improvement on the reasoning task after only one training epoch. The most significant gain appears in Rouge 2 scores—which measure bigram overlap—with about 49% increase, indicating better alignment between generated and reference summaries.
Notably, preliminary experiments suggest these results could be further enhanced by extending the training duration. Increasing the number of epochs shows promising potential for additional performance gains while maintaining computational efficiency.
Clean up
To clean up your resources to avoid incurring any more charges, follow these steps:

Delete any unused SageMaker Studio resources
(Optional) Delete the SageMaker Studio domain
Verify that your training job isn’t running anymore. To do so, on your SageMaker console, choose Training and check Training jobs.
If you created a HyperPod cluster, delete the cluster to stop incurring costs. If you created the networking stack from the HyperPod workshop, delete the stack as well to clean up the virtual private cloud (VPC) resources and the FSx for Lustre volume.

Conclusion
In the first post of this two-part DeepSeek-R1 series, we discussed how SageMaker HyperPod recipes provide a powerful yet accessible solution for organizations to scale their AI model training capabilities with large language models (LLMs) including DeepSeek. The architecture streamlines complex distributed training workflows through its intuitive recipe-based approach, reducing setup time from weeks to minutes.
We recommend starting your LLM customization journey by exploring our sample recipes in the Amazon SageMaker HyperPod documentation. The AWS AI/ML community offers extensive resources, including workshops and technical guidance, to support your implementation journey.
To begin using the SageMaker HyperPod recipes, visit the sagemaker-hyperpod-recipes repo on GitHub for comprehensive documentation and example implementations. Our team continues to expand the recipe ecosystem based on customer feedback and emerging ML trends, making sure that you have the tools needed for successful AI model training.
In our second post, we discuss how these recipes could further be used to fine-tune DeepSeek-R1 671b model. Stay tuned!

About the Authors
 Kanwaljit Khurmi is a Principal Worldwide Generative AI Solutions Architect at AWS. He collaborates with AWS product teams, engineering departments, and customers to provide guidance and technical assistance, helping them enhance the value of their hybrid machine learning solutions on AWS. Kanwaljit specializes in assisting customers with containerized applications and high-performance computing solutions.
 Bruno Pistone is a Senior World Wide Generative AI/ML Specialist Solutions Architect at AWS based in Milan, Italy. He works with AWS product teams and large customers to help them fully understand their technical needs and design AI and Machine Learning solutions that take full advantage of the AWS cloud and Amazon Machine Learning stack. His expertise includes: End-to-end Machine Learning, model customization, and generative AI. He enjoys spending time with friends, exploring new places, and traveling to new destinations.
 Arun Kumar Lokanatha is a Senior ML Solutions Architect with the Amazon SageMaker team. He specializes in large language model training workloads, helping customers build LLM workloads using SageMaker HyperPod, SageMaker training jobs, and SageMaker distributed training. Outside of work, he enjoys running, hiking, and cooking.
 Durga Sury is a Senior Solutions Architect on the Amazon SageMaker team. Over the past 5 years, she has worked with multiple enterprise customers to set up a secure, scalable AI/ML platform built on SageMaker.
 Aman Shanbhag is an Associate Specialist Solutions Architect on the ML Frameworks team at Amazon Web Services, where he helps customers and partners with deploying ML training and inference solutions at scale. Before joining AWS, Aman graduated from Rice University with degrees in computer science, mathematics, and entrepreneurship.
Anirudh Viswanathan is a Sr Product Manager, Technical – External Services with the SageMaker AI Training team. He holds a Masters in Robotics from Carnegie Mellon University, an MBA from the Wharton School of Business, and is named inventor on over 40 patents. He enjoys long-distance running, visiting art galleries, and Broadway shows.

Reduce conversational AI response time through inference at the edge w …

Recent advances in generative AI have led to the proliferation of new generation of conversational AI assistants powered by foundation models (FMs). These latency-sensitive applications enable real-time text and voice interactions, responding naturally to human conversations. Their applications span a variety of sectors, including customer service, healthcare, education, personal and business productivity, and many others.
Conversational AI assistants are typically deployed directly on users’ devices, such as smartphones, tablets, or desktop computers, enabling quick, local processing of voice or text input. However, the FM that powers the assistant’s natural language understanding and response generation is usually cloud-hosted, running on powerful GPUs. When a user interacts with the AI assistant, their device first processes the input locally, including speech-to-text (STT) conversion for voice agents, and compiles a prompt. This prompt is then securely transmitted to the cloud-based FM over the network. The FM analyzes the prompt and begins generating an appropriate response, streaming it back to the user’s device. The device further processes this response, including text-to-speech (TTS) conversion for voice agents, before presenting it to the user. This efficient workflow strikes a balance between the powerful capabilities of cloud-based FMs and the convenience and responsiveness of local device interaction, as illustrated in the following figure.
A critical challenge in developing such applications is reducing response latency to enable real-time, natural interactions. Response latency refers to the time between the user finishing their speech and beginning to hear the AI assistant’s response. This delay typically comprises two primary components:

On-device processing latency – This encompasses the time required for local processing, including TTS and STT operations.
Time to first token (TTFT) – This measures the interval between the device sending a prompt to the cloud and receiving the first token of the response. TTFT consists of two components. First is the network latency, which is the round-trip time for data transmission between the device and the cloud. Second is the first token generation time, which is the period between the FM receiving a complete prompt and generating the first output token. TTFT is crucial for user experience in conversational AI interfaces that use response streaming with FMs. With response streaming, users start receiving the response while it’s still being generated, significantly improving perceived latency.

The ideal response latency for humanlike conversation flow is generally considered to be in the 200–500 milliseconds (ms) range, closely mimicking natural pauses in human conversation. Given the additional on-device processing latency, achieving this target requires a TTFT well below 200 ms.
Although many customers focus on optimizing the technology stack behind the FM inference endpoint through techniques such as model optimization, hardware acceleration, and semantic caching to reduce the TTFT, they often overlook the significant impact of network latency. This latency can vary considerably due to geographic distance between users and cloud services, as well as the diverse quality of internet connectivity.
Hybrid architecture with AWS Local Zones
To minimize the impact of network latency on TTFT for users regardless of their locations, a hybrid architecture can be implemented by extending AWS services from commercial Regions to edge locations closer to end users. This approach involves deploying additional inference endpoints on AWS edge services and using Amazon Route 53 to implement dynamic routing policies, such as geolocation routing, geoproximity routing, or latency-based routing. These strategies dynamically distribute traffic between edge locations and commercial Regions, providing fast response times based on real-time network conditions and user locations.
AWS Local Zones are a type of edge infrastructure deployment that places select AWS services close to large population and industry centers. They enable applications requiring very low latency or local data processing using familiar APIs and tool sets. Each Local Zone is a logical extension of a corresponding parent AWS Region, which means customers can extend their Amazon Virtual Private Cloud (Amazon VPC) connections by creating a new subnet with a Local Zone assignment.
This guide demonstrates how to deploy an open source FM from Hugging Face on Amazon Elastic Compute Cloud (Amazon EC2) instances across three locations: a commercial AWS Region and two AWS Local Zones. Through comparative benchmarking tests, we illustrate how deploying FMs in Local Zones closer to end users can significantly reduce latency—a critical factor for real-time applications such as conversational AI assistants.
Prerequisites
To run this demo, complete the following prerequisites:

Create an AWS account, if you don’t already have one.
Enable the Local Zones in Los Angeles and Honolulu in the parent Region US West (Oregon). For a full list of available Local Zones, refer to the Local Zones locations page. Next, create a subnet inside each Local Zone. Detailed instructions for enabling Local Zones and creating subnets within them can be found at Getting started with AWS Local Zones.
Submit an Amazon EC2 service quota increase for access to Amazon EC2 G4dn instances. Select the Running On-Demand G and VT instances as the quota type and at least 24 vCPUs for the quota size.
Create a Hugging Face read token from huggingface.co/settings/tokens.

Solution walkthrough
This section walks you through the steps to launch an Amazon EC2 G4dn instance and deploy an FM for inference in the Los Angeles Local Zone. The instructions are also applicable for deployments in the parent Region, US West (Oregon), and the Honolulu Local Zone.
We use Meta’s open source Llama 3.2-3B as the FM for this demonstration. This is a lightweight FM from the Llama 3.2 family, classified as a small language model (SLM) due to its small number of parameters. Compared to large language models (LLMs), SLMs are more efficient and cost-effective to train and deploy, excel when fine-tuned for specific tasks, offer faster inference times, and have lower resource requirements. These characteristics make SLMs particularly well-suited for deployment on edge services such as AWS Local Zones.
To launch an EC2 instance in the Los Angeles Local Zone subnet, follow these steps:

On the Amazon EC2 console dashboard, in the Launch instance box, choose Launch instance.
Under Name and tags, enter a descriptive name for the instance (for example, la-local-zone-instance).
Under Application and OS Images (Amazon Machine Image), select an AWS Deep Learning AMI that comes preconfigured with NVIDIA OSS driver and PyTorch. For our deployment, we used Deep Learning OSS Nvidia Driver AMI GPU PyTorch 2.3.1 (Amazon Linux 2).
Under Instance type, from the Instance type list, select the hardware configuration for your instance that’s supported in a Local Zone. We selected G4dn.2xlarge for this solution. This instance is equipped with one NVIDIA T4 Tensor Core GPU and 16 GB of GPU memory, which makes it ideal for high performance and cost-effective inference of SLMs on the edge. Available instance types for each Local Zone can be found at AWS Local Zones features. Review the hardware requirements for your FM to select the appropriate instance.
Under Key pair (login), choose an existing key pair or create a new one.
Next to Network settings, choose Edit, and then:

Select your VPC.
Select your Local Zone subnet.
Create a security group or select an existing one. Configure the security group’s inbound rules to allow traffic only from your client’s IP address on port 8080.

You can keep the default selections for the other configuration settings for your instance. To determine the storage types that are supported, refer to the Compute and storage section in AWS Local Zones features.
Review the summary of your instance configuration in the Summary panel and, when you’re ready, choose Launch instance.
A confirmation page lets you know that your instance is launching. Choose View all instances to close the confirmation page and return to the console.

Next, complete the following steps to deploy Llama 3.2-3B using the Hugging Face Text Generation Inference (TGI) as the model server:

Connect by using Secure Shell (SSH) into the instance
Start the docker service using the following command. This comes preinstalled with the AMI we selected.

sudo service docker start

Run the following command to download and run the Docker image for TGI server as well as Llama 3.2-3B model. In our deployment, we used Docker image version 2.4.0, but results might vary based on your selected version. The full list of supported models by TGI can be found at Hugging Face Supported Models. For more details about the deployment and optimization of TGI, refer to this text-generation-inference GitHub page.

model=meta-llama/Llama-3.2-3B
volume=$PWD/data
token=<ENTER YOUR HUGGING FACE TOKEN>

sudo docker run -d –gpus all
–shm-size 1g
-e HF_TOKEN=$token
-p 8080:80
-v $volume:/data ghcr.io/huggingface/text-generation-inference:2.4.0
–model-id $model

After the TGI container is running, you can test your endpoint by running the following command from your local environment:

curl <REPLACE WITH YOUR EC2 PUBLIC IP >:8080/generate -X POST
-d ‘{“inputs”:”What is deep learning?”,”parameters”:{“max_new_tokens”:200, “temperature”:0.2, “top_p”:0.9}}’
-H ‘Content-Type: application/json’
Performance evaluation
To demonstrate TTFT improvements with FM inference on Local Zones, we followed the steps in the previous section to deploy Llama 3.2 3B in three locations: in the us-west-2-c Availability Zone in the parent Region, US West (Oregon); in the us-west-2-lax-1a Local Zone in Los Angeles; and in the us-west-2-hnl-1a Local Zone in Honolulu. This is illustrated in the following figure. Notice that the architecture provided in this post is meant to be used for performance evaluation in a development environment. Before migrating any of the provided architecture to production, we recommend following the AWS Well-Architected Framework.
We conducted two separate test scenarios to evaluate TTFT as explained in the following:
Los Angeles test scenario:

Test user’s location – Los Angeles metropolitan area
Test A – 150 requests sent to FM deployed in Los Angeles Local Zone
Test B – 150 requests sent to FM deployed in US West (Oregon)

Honolulu test scenario:

Test user’s location – Honolulu metropolitan area
Test C – 150 requests sent to FM deployed in Honolulu Local Zone
Test D – 150 requests sent to FM deployed in US West (Oregon)

Evaluation setup
To conduct TTFT measurements, we use the load testing capabilities of the open source project LLMPerf. This tool launches multiple requests from the test user’s client to the FM endpoint and measures various performance metrics, including TTFT. Each request contains a random prompt with a mean token count of 250 tokens. Although a single prompt for short-form conversations typically consists of 50 tokens, we set the mean input token size to 250 tokens to account for multi-turn conversation history, system prompts, and contextual information that better represents real-world usage patterns.
Detailed instructions for installing LLMPerf and executing the load testing are available in the project’s documentation. Additionally, because we are using the Hugging Face TGI as the inference server, we follow the corresponding instructions from LLMPerf to perform the load testing. The following is the example command to initiate the load testing from the command line:

export HUGGINGFACE_API_BASE=”http://<REPLACE WITH YOUR EC2 PUBLIC IP>:8080″
export HUGGINGFACE_API_KEY=””

python token_benchmark_ray.py
    –model “huggingface/meta-llama/Llama-3.2-3B”
    –mean-input-tokens 250
    –stddev-input-tokens 50
    –mean-output-tokens 100
    –stddev-output-tokens 20
    –max-num-completed-requests 150
    –timeout 600
    –num-concurrent-requests 1
    –results-dir “result_outputs”
    –llm-api “litellm”
    –additional-sampling-params ‘{}’

Each test scenario compares the TTFT latency between Local Zone and the parent Region endpoints to assess the impact of geographical distance. Latency results might vary based on several factors, including:

Test parameters and configuration
Time of day and network traffic
Internet service provider
Specific client location within the test Region
Current server load

Results
The following tables below present TTFT measurements in milliseconds (ms) for two distinct test scenarios. The results demonstrate significant TTFT reductions when using a Local Zone compared to the parent Region for both the Los Angeles and the Honolulu test scenarios. The observed differences in TTFT are solely attributed to network latency because identical FM inference configurations were employed in both the Local Zone and the parent Region.

User location: Los Angeles Metropolitan Area

LLM inference endpoint
Mean (ms)
Min (ms)
P25 (ms)
P50 (ms)
P75 (ms)
P95 (ms)
P99 (ms)
Max (ms)

Parent Region: US West (Oregon)
135
118
125
130
139
165
197
288

Local Zone: Los Angeles
80
50
72
75
86
116
141
232

The user in Los Angeles achieved a mean TTFT of 80 ms when calling the FM endpoint in the Los Angeles Local Zone, compared to 135 ms for the endpoint in the US West (Oregon) Region. This represents a 55 ms (about 41%) reduction in latency.

User location: Honolulu Metropolitan Area

LLM inference endpoint
Mean (ms)
Min (ms)
P25 (ms)
P50 (ms)
P75 (ms)
P95 (ms)
P99 (ms)
Max (ms)

Parent Region: US West (Oregon)
197
172
180
183
187
243
472
683

Local Zone: Honolulu
114
58
70
85
164
209
273
369

The user in Honolulu achieved a mean TTFT of 114 ms when calling the FM endpoint in the Honolulu Local Zone, compared to 197 ms for the endpoint in the US West (Oregon) Region. This represents an 83 ms (about 42%) reduction in latency.
Moreover, the TTFT reduction achieved by Local Zone deployments is consistent across all metrics in both test scenarios, from minimum to maximum values and throughout all percentiles (P25–P99), indicating a consistent improvement across all requests.
Finally, remember that TTFT is just one component of overall response latency, alongside on-device processing latency. By reducing TTFT using Local Zones, you create additional margin for on-device processing latency, making it easier to achieve the target response latency range needed for humanlike conversation.
Cleanup
In this post, we created Local Zones, subnets, security groups, and EC2 instances. To avoid incurring additional charges, it’s crucial to properly clean up these resources when they’re no longer needed. To do so, follow these steps:

Terminate the EC2 instances and delete their associated Amazon Elastic Block Store (Amazon EBS) volumes.
Delete the security groups and subnets.
Disable the Local Zones.

Conclusion
In conclusion, this post highlights how edge computing services, such as AWS Local Zones, play a crucial role in reducing FM inference latency for conversational AI applications. Our test deployments of Meta’s Llama 3.2-3B demonstrated that placing FM inference endpoints closer to end users through Local Zones dramatically reduces TTFT compared to traditional Regional deployments. This TTFT reduction plays a critical role in optimizing the overall response latency, helping achieve the target response times essential for natural, humanlike interactions regardless of user location.
To use these benefits for your own applications, we encourage you to explore the AWS Local Zones documentation. There, you’ll find information on available locations and supported AWS services so you can bring the power of edge computing to your conversational AI solutions.

About the Authors
Nima Seifi is a Solutions Architect at AWS, based in Southern California, where he specializes in SaaS and LLMOps. He serves as a technical advisor to startups building on AWS. Prior to AWS, he worked as a DevOps architect in the e-commerce industry for over 5 years, following a decade of R&D work in mobile internet technologies. Nima has authored 20+ technical publications and holds 7 U.S. patents. Outside of work, he enjoys reading, watching documentaries, and taking beach walks.
Nelson Ong is a Solutions Architect at Amazon Web Services. He works with early stage startups across industries to accelerate their cloud adoption.

Pixtral-12B-2409 is now available on Amazon Bedrock Marketplace

Today, we are excited to announce that Pixtral 12B (pixtral-12b-2409), a state-of-the-art 12 billion parameter vision language model (VLM) from Mistral AI that excels in both text-only and multimodal tasks, is available for customers through Amazon Bedrock Marketplace. Amazon Bedrock Marketplace is a new capability in Amazon Bedrock that enables developers to discover, test, and use over 100 popular, emerging, and specialized foundation models (FMs) alongside the current selection of industry-leading models in Amazon Bedrock. You can also use this model with Amazon SageMaker JumpStart, a machine learning (ML) hub that provides access to algorithms and models that can be deployed with one click for running inference.
In this post, we walk through how to discover, deploy, and use the Pixtral 12B model for a variety of real-world vision use cases.
Overview of Pixtral 12B
Pixtral 12B, Mistral’s inaugural VLM, delivers robust performance across a range of benchmarks, surpassing other open models and rivaling larger counterparts, according to Mistral’s evaluation. Designed for both image and document comprehension, Pixtral demonstrates advanced capabilities in vision-related tasks, including chart and figure interpretation, document question answering, multimodal reasoning, and instruction following—several of which are illustrated with examples later in this post. The model processes images at their native resolution and aspect ratio, providing high-fidelity input handling. Unlike many open source alternatives, Pixtral 12B achieves strong results in text-based benchmarks—such as instruction following, coding, and mathematical reasoning—without sacrificing its proficiency in multimodal tasks.
Mistral developed a novel architecture for Pixtral 12B, optimized for both computational efficiency and performance. The model consists of two main components: a 400-million-parameter vision encoder, responsible for tokenizing images, and a 12-billion-parameter multimodal transformer decoder, which predicts the next text token based on a sequence of text and images. The vision encoder was specifically trained to natively handle variable image sizes, enabling Pixtral to accurately interpret high-resolution diagrams, charts, and documents while maintaining fast inference speeds for smaller images such as icons, clipart, and equations. This architecture supports processing an arbitrary number of images of varying sizes within a large context window of 128k tokens.
License agreements are a critical decision factor when using open-weights models. Similar to other Mistral models, such as Mistral 7B, Mixtral 8x7B, Mixtral 8x22B, and Mistral Nemo 12B, Pixtral 12B is released under the commercially permissive Apache 2.0, providing enterprise and startup customers with a high-performing VLM option to build complex multimodal applications.
Performance metrics and benchmarks
Pixtral 12B is trained to understand both natural images and documents, achieving 52.5% on the Massive Multitask Language Understanding (MMLU) reasoning benchmark, surpassing a number of larger models according to Mistral. The MMLU benchmark is a test that evaluates a language model’s ability to understand and use language across a variety of subjects. The MMLU consists of over 10,000 multiple-choice questions spanning a variety of academic subjects, including mathematics, philosophy, law, and medicine. The model shows strong abilities in tasks such as chart and figure understanding, document question answering, multimodal reasoning, and instruction following. Pixtral is able to ingest images at their natural resolution and aspect ratio, giving the user flexibility on the number of tokens used to process an image. Pixtral is also able to process multiple images in its long context window of 128,000 tokens. Unlike previous open source models, Pixtral doesn’t compromise on text benchmark performance to excel in multimodal tasks, according to Mistral.
You can review the Mistral published benchmarks
Prerequisites
To try out Pixtral 12B in Amazon Bedrock Marketplace, you will need the following prerequisites:

An AWS account that will contain all your AWS resources.
An AWS Identity and Access Management (IAM) role to access Amazon Bedrock Marketplace and Amazon SageMaker endpoints. To learn more about how IAM works with Amazon Bedrock Marketplace, refer to Set up Amazon Bedrock Marketplace.
Access to accelerated instances (GPUs) for hosting the model, such as ml.g6.12xlarge. Refer to Requesting a quota increase for access to GPU instances.

Deploy Pixtral 12B in Amazon Bedrock Marketplace
On the Amazon Bedrock console, you can search for models that help you with a specific use case or language. The results of the search include both serverless models and models available in Amazon Bedrock Marketplace. You can filter results by provider, modality (such as text, image, or audio), or task (such as classification or text summarization).
To access Pixtral 12B in Amazon Bedrock Marketplace, follow these steps:

On the Amazon Bedrock console, choose Model catalog under Foundation models in the navigation pane.
Filter for Hugging Face as a provider and choose the Pixtral 12B model, or search for Pixtral in the Filter for a model input box.

The model detail page provides essential information about the model’s capabilities, pricing structure, and implementation guidelines. You can find detailed usage instructions, including sample API calls and code snippets for integration.
The page also includes deployment options and licensing information to help you get started with Pixtral 12B in your applications.

To begin using Pixtral 12B, choose Deploy.

You will be prompted to configure the deployment details for Pixtral 12B. The model ID will be prepopulated.

Read carefully and accept the End User License Agreement (EULA).
The Endpoint Name is automatically populated. Customers can choose to rename the endpoint.
For Number of instances, enter a number of instances (between 1–100).
For Instance type, choose your instance type. For optimal performance with Pixtral 12B, a GPU-based instance type like ml.g6.12xlarge is recommended.

Optionally, you can configure advanced security and infrastructure settings, including virtual private cloud (VPC) networking, service role permissions, and encryption settings. For most use cases, the default settings will work well. However, for production deployments, you might want to review these settings to align with your organization’s security and compliance requirements.

Choose Deploy to begin using the model.

When the deployment is complete, Endpoint status should change to In Service. After the endpoint is in service, you can test Pixtral 12B capabilities directly in the Amazon Bedrock playground.

Choose Open in playground to access an interactive interface where you can experiment with different prompts and adjust model parameters like temperature and maximum length.

This is an excellent way to explore the model’s reasoning and text generation abilities before integrating it into your applications. The playground provides immediate feedback, helping you understand how the model responds to various inputs and letting you fine-tune your prompts for optimal results.

You can quickly test the model in the playground through the UI. However, to invoke the deployed model programmatically with Amazon Bedrock APIs, you need to use the endpoint ARN as model-id in the Amazon Bedrock SDK.
Pixtral 12B use cases
In this section, we provide example use cases of Pixtral 12B using sample prompts. We have defined helper functions to invoke the Pixtral 12B model using Amazon Bedrock Converse APIs:

def get_image_format(image_path):
with Image.open(image_path) as img:
# Normalize the format to a known valid one
fmt = img.format.lower() if img.format else ‘jpeg’
# Convert ‘jpg’ to ‘jpeg’
if fmt == ‘jpg’:
fmt = ‘jpeg’
return fmt

def call_bedrock_model(model_id=None, prompt=””, image_paths=None, system_prompt=””, temperature=0.6, top_p=0.9, max_tokens=3000):

if isinstance(image_paths, str):
image_paths = [image_paths]
if image_paths is None:
image_paths = []

# Start building the content array for the user message
content_blocks = []

# Include a text block if prompt is provided
if prompt.strip():
content_blocks.append({“text”: prompt})

# Add images as raw bytes
for img_path in image_paths:
fmt = get_image_format(img_path)
# Read the raw bytes of the image (no base64 encoding!)
with open(img_path, ‘rb’) as f:
image_raw_bytes = f.read()

content_blocks.append({
“image”: {
“format”: fmt,
“source”: {
“bytes”: image_raw_bytes
}
}
})

# Construct the messages structure
messages = [
{
“role”: “user”,
“content”: content_blocks
}
]

# Prepare additional kwargs if system prompts are provided
kwargs = {}

kwargs[“system”] = [{“text”: system_prompt}]

# Build the arguments for the `converse` call
converse_kwargs = {
“messages”: messages,
“inferenceConfig”: {
“maxTokens”: 4000,
“temperature”: temperature,
“topP”: top_p
},
**kwargs
}

converse_kwargs[“modelId”] = model_id

# Call the converse API
try:
response = bedrock_runtime.converse(**converse_kwargs)

# Parse the assistant response
assistant_message = response.get(‘output’, {}).get(‘message’, {})
assistant_content = assistant_message.get(‘content’, [])
result_text = “”.join(block.get(‘text’, ”) for block in assistant_content)
except Exception as e:
result_text = f”Error message: {e}”
return result_text

Visual logical reasoning
One of the interesting use cases of vision models is solving logical reasoning problems or visual puzzles. Pixtral 12B vision models are highly capable in solving logical reasoning questions. Let’s explore an example.
We use the following input image.

Our prompt and input payload are as follows:

system_prompt=’You are solving logical reasoning problems.’
task = ‘Which of these figures differ from the other four?’
image_path = ‘./Pixtral_data/logical_reasoning.jpg’

print(‘Input Image:nn’)
Image.open(image_path).show()

response = call_bedrock_model(model_id=endpoint_arn,
prompt=task,
system_prompt=system_prompt,
image_paths = image_path)

print(f’nResponse from the model:nn{response}’)

We get following response:

The image shows five figures labeled A, B, C, D, and E. Each figure consists of a head, body, and legs. The task is to identify which figure differs from the others.

**Reasoning:**
– Figure A: The head is connected directly to the body, and the legs are straight.
– Figure B: The head is connected directly to the body, and the legs are straight.
– Figure C: The head is connected directly to the body, and the legs are straight.
– Figure D: The head is connected directly to the body, and the legs are straight.
– Figure E: The head is connected directly to the body, but the legs are bent at the knees.

**Conclusion:** Figure E is the one that differs from the others.

Structured product information
Extracting product information is crucial for the retail industry, especially on sites that host third-party sellers, where product images are the most accessible resource. Accurately capturing relevant details from these images is vital for a product’s success in ecommerce. For instance, using advanced visual models like Pixtral 12B, retailers can efficiently extract key attributes from clothing product images, such as color, style, and patterns. This capability not only streamlines inventory management but also enhances customer experiences by providing essential information that aids in informed purchasing decisions.
We use the following input image.

Our prompt and input payload are as follows:

system_prompt=”’You are a catalog manager for an ecommerce portal. You have an image of a product.
Think very carefully in a step-by-step manner to extract product information.
Always provide response in prescribed JSON format.
”’
image_path = ‘./Pixtral_data/cap.png’
task = ”’
Organize product information in JSON format to store in a database.

Output json schema:

{
“product_name”: “”,
“description”: “”,
“category”: “”,
“sub_category”: “”,
“color”: “”,
“size”: “”,
“brand”: “”,
“material”: “”,
“features”: [],
“image_alt_text”: “”
}
”’

print(‘Input Image:nn’)
Image.open(image_path).show()

response = call_bedrock_model(model_id=endpoint_arn,
prompt=task,
system_prompt=system_prompt,
image_paths = image_path)

print(f’nResponse from the model:nn{response}’)

We get the following response:

Certainly! Based on the image provided, here is the extracted product information in JSON format:

“`json
{
“product_name”: “Nike Blue Cap”,
“description”: “A stylish blue cap from Nike with a sleek design and adjustable fit.”,
“category”: “Apparel”,
“sub_category”: “Headwear”,
“color”: “Blue”,
“size”: “Adjustable”,
“brand”: “Nike”,
“material”: “Nylon”,
“features”: [
“Adjustable fit”,
“Lightweight”,
“Breathable material”,
“Embroidered Nike logo”
],
“image_alt_text”: “A blue Nike cap with a white Nike swoosh logo on the front.”
}
“`

Vehicle damage assessment
In the insurance industry, image analysis plays a crucial role in claims processing. For vehicle damage assessment, vision models like Pixtral 12B can be used to compare images taken at policy issuance with those submitted during a claim. This approach can streamline the evaluation process, potentially reducing loss adjustment expenses and expediting claim resolution. By automating the identification and characterization of automobile damage, insurers can enhance efficiency, improve accuracy, and ultimately provide a better experience for policyholders.
We use the following input images.

Our prompt and input payload are as follows:

image_paths = [
“Pixtral_data/car_image_before.png”,
“Pixtral_data/car_image_after.png”
]

system_prompt=”’
You are a helpful ai assistant for an insurance agent.
Insurance agent has received a claim for a vehicle damage.
”’

task = ”’This claim includes two images.
One of the image was taken before the incident and another was taken after the incident.

Analyse these images and answer below questions:
1. describe if there is any damage to the vehicle
2. should insurance agent accept or reject the claim

”’

print(‘Input Images:nn’)
Image.open(image_paths[0]).show()
Image.open(image_paths[1]).show()

response = call_bedrock_model(model_id=endpoint_arn,
prompt=task,
system_prompt=system_prompt,
image_paths = image_paths)

print(f’nResponse from the model:nn{response}’)

We get the following response:

### Analysis of Vehicle Damage

#### Image 1 (Before Incident)
– **Vehicle Condition**: The vehicle appears to be in good condition with no visible damage.
– **Paint and Body**: The paint is uniform, and there are no visible scratches, dents, or other forms of damage.
– **Tires and Wheels**: The tires and wheels look intact and in good condition.

#### Image 2 (After Incident)
– **Vehicle Condition**: The vehicle shows noticeable damage.
– **Paint and Body**: There is a visible dent or scratch on the rear side of the vehicle.
– **Tires and Wheels**: The tires and wheels appear to be intact, but the focus is on the body damage.

### Questions and Answers

1. **Describe if there is any damage to the vehicle:**
– **Before Incident**: No visible damage.
– **After Incident**: There is visible damage on the rear side of the vehicle, likely a dent or scratch.

2. **Should the insurance agent accept or reject the claim:**
– **Recommendation**: The insurance agent should accept the claim. The images clearly show that the vehicle sustained damage after the incident. The before and after images provide sufficient evidence of the damage, which was likely caused by an incident.

### Conclusion
Based on the analysis of the images, the insurance agent should accept the claim as the damage to the vehicle is evident and appears to have occurred after the incident.

Handwriting recognition
Another feature in vision language models is their ability to recognize handwriting and extract handwritten text. Pixtral 12B performs well on extracting content from complex and poorly handwritten notes.
We use the following input image.
Our prompt and input payload are as follows:

system_prompt=’You are a Graphologists’
task = ”’
Analyze the image and transcribe any handwritten text present.
Convert the handwriting into a single, continuous string of text.
Maintain the original spelling, punctuation, and capitalization as written. Ignore any printed text, drawings, or other non-handwritten elements in the image.
”’

image_path = ‘./Pixtral_data/a01-000u-04.png’

print(‘Input Image:nn’)
Image.open(image_path).show()

response = call_bedrock_model(model_id=endpoint_arn,
prompt=task,
system_prompt=system_prompt,
image_paths = image_path)

print(f’nResponse from the model:nn{response}’)

We get the following response:

put down a resolution on the subject

Reasoning of complex figures
VLMs excel at interpreting and reasoning about complex figures, charts, and diagrams. In this particular use case, we use Pixtral 12B to analyze an intricate image containing GDP data. Pixtral 12B’s advanced capabilities in document understanding and complex figure analysis make it well-suited for extracting insights from visual representations of economic data. By processing both the visual elements and accompanying text, Pixtral 12B can provide detailed interpretations and reasoned analysis of the GDP figures presented in the image.
We use the following input image.

Our prompt and input payload are as follows:

system_prompt=’You are a Global Economist.’
task = ‘List the top 5 countries in Europe with the highest GDP’
image_path = ‘./Pixtral_data/gdp.png’

print(‘Input Image:nn’)
Image.open(image_path).show()

response = call_bedrock_model(model_id=endpoint_arn,
prompt=task,
system_prompt=system_prompt,
image_paths = image_path)

print(f’nResponse from the model:nn{response}’)

We get the following response:

The top 5 countries in Europe with the highest GDP, based on the provided diagram, are:

1. **Germany**
– GDP: $3.99 trillion
– GDP Percentage: 4.65%

2. **United Kingdom**
– GDP: $2.82 trillion
– GDP Percentage: 3.29%

3. **France**
– GDP: $2.78 trillion
– GDP Percentage: 3.24%

4. **Italy**
– GDP: $2.07 trillion
– GDP Percentage: 2.42%

5. **Spain**
– GDP: $1.43 trillion
– GDP Percentage: 1.66%

These countries are highlighted in green on the diagram.

Clean up
To avoid unwanted charges, clean up your resources. If you deployed the model using Amazon Bedrock Marketplace, complete the following steps:
Delete the Amazon Bedrock Marketplace deployment

On the Amazon Bedrock console, under Foundation models in the navigation pane, choose Marketplace deployments.
In the Managed deployments section, locate the endpoint you want to delete.
Verify the endpoint details to make sure you’re deleting the correct deployment:

Endpoint name
Model name
Endpoint status

Select the endpoint, and choose Delete.
Choose Delete to delete the endpoint.
In the deletion confirmation dialog, review the warning message, enter confirm, and choose Delete to permanently remove the endpoint.

Conclusion
In this post, we showed you how to get started with the Pixtral 12B model in Amazon Bedrock and deploy the model for inference. The Pixtral 12B vision model enables you to solve multiple use cases, including document understanding, logical reasoning, handwriting recognition, image comparison, entity extraction, extraction of structured data from scanned images, and caption generation. These capabilities can drive productivity in a number of enterprise use cases, including ecommerce (retail), marketing, FSI, and much more.
For more Mistral resources on AWS, check out the GitHub repo. The complete code for the samples featured in this post is available on GitHub. Pixtral 12B is also available in Amazon SageMaker JumpStart; refer to Pixtral 12B is now available on Amazon SageMaker JumpStart for details.

About the Authors
Deepesh Dhapola is a Senior Solutions Architect at AWS India, where he assists financial services and fintech clients in scaling and optimizing their applications on the AWS platform. He specializes in core machine learning and generative AI. Outside of work, Deepesh enjoys spending time with his family and experimenting with various cuisines.
Preston Tuggle is a Sr. Specialist Solutions Architect working on generative AI.
Shane Rai is a Principal GenAI Specialist with the AWS World Wide Specialist Organization (WWSO). He works with customers across industries to solve their most pressing and innovative business needs using AWS’s breadth of cloud-based AI/ML services including model offerings from top tier foundation model providers.
John Liu has 14 years of experience as a product executive and 10 years of experience as a portfolio manager. At AWS, John is a Principal Product Manager for Amazon Bedrock. Previously, he was the Head of Product for AWS Web3 / Blockchain. Prior to AWS, John held various product leadership roles at public blockchain protocols and fintech companies, and also spent 9 years as a portfolio manager at various hedge funds.

Researchers from UCLA, UC Merced and Adobe propose METAL: A Multi-Agen …

Creating charts that accurately reflect complex data remains a nuanced challenge in today’s data visualization landscape. Often, the task involves not only capturing precise layouts, colors, and text placements but also translating these visual details into code that reproduces the intended design. Traditional methods, which rely on direct prompting of vision-language models (VLMs) such as GPT-4V, frequently encounter difficulties when converting intricate visual elements into syntactically correct Python code. The process requires both a strong visual design sensibility and careful coding—two areas where even small discrepancies can lead to charts that fail to meet their design objectives. Such challenges are especially relevant in fields like financial analysis, academic research, and educational reporting, where clarity and accuracy in data representation are paramount.

METAL: A Thoughtful Multi-Agent Framework

Researchers from UCLA, UC Merced, and Adobe Research propose a new framework called METAL. This system divides the chart generation task into a series of focused steps managed by specialized agents. METAL comprises four key agents: the Generation Agent, which produces the initial Python code; the Visual Critique Agent, which evaluates the generated chart against a reference; the Code Critique Agent, which reviews the underlying code; and the Revision Agent, which refines the code based on the feedback received. By assigning each of these roles to an agent, METAL enables a more deliberate and iterative approach to chart creation. This structured method helps ensure that both the visual and technical elements of a chart are carefully considered and adjusted, leading to outputs that more faithfully mirror the original reference.

Technical Insights and Practical Benefits

One of the distinguishing features of METAL is its modular design. Instead of expecting a single model to handle both visual interpretation and code generation, the framework distributes these responsibilities among dedicated agents. The Generation Agent begins by converting visual information into a preliminary set of Python instructions. The Visual Critique Agent then scrutinizes the rendered chart, identifying discrepancies in design elements such as layout or color fidelity. Simultaneously, the Code Critique Agent inspects the generated code to catch any syntactical errors or logical issues that might undermine the chart’s accuracy. Finally, the Revision Agent takes into account the feedback from both critique agents and adjusts the code accordingly.

Another notable aspect of METAL is its approach to resource scaling at test time. The framework’s performance has been observed to improve in a near-linear fashion as the logarithmic computational budget increases—from 512 to 8192 tokens. This relationship implies that when additional computational resources are available, the framework is capable of producing even more refined outputs. By iteratively refining the code and chart with each pass, METAL achieves an enhanced level of accuracy without sacrificing clarity or detail.

Experimental Insights and Measured Outcomes

The performance of METAL has been evaluated on the ChartMIMIC dataset, which contains carefully curated examples of charts along with their corresponding generation instructions. The evaluation focused on key aspects such as text clarity, chart type accuracy, color consistency, and layout precision. In comparisons with more traditional approaches—such as direct prompting and enhanced hinting methods—METAL demonstrated improvements in replicating the reference charts. For instance, when tested on open-source models like LLAMA 3.2-11B, METAL produced outputs that were, on average, closer in accuracy to the reference charts than those generated by conventional methods. Similar patterns were observed with closed-source models like GPT-4O, where the incremental refinements led to outputs that were both more precise and visually consistent.

A further analysis involving ablation studies highlighted the importance of maintaining distinct critique mechanisms for visual and code aspects. When these components were merged into a single critique agent, the performance tended to decline. This observation suggests that a tailored approach—where the nuances of visual design and code correctness are addressed separately—plays a key role in ensuring high-quality chart generation.

Conclusion: A Measured Approach to Enhanced Chart Generation

In summary, METAL offers a balanced, multi-agent approach to the challenge of chart generation by decomposing the task into specialized, iterative steps. Rather than relying on a single model to manage both the artistic and technical dimensions of the task, METAL distributes the workload among agents dedicated to generation, visual critique, code critique, and revision. This method not only facilitates a more careful translation of visual designs into Python code but also allows for a systematic process of error detection and correction.

Moreover, the framework’s capacity to improve with increased computational resources—illustrated by its near-linear scaling with additional tokens—underscores its practical potential in settings where precision is crucial. While there is still room for optimization, particularly in reducing the computational overhead and further fine-tuning the prompt engineering, METAL represents a thoughtful step forward. Its emphasis on a measured, iterative refinement process makes it a promising tool for applications where reliable chart generation is essential.

Check out the Paper, Code and Project Page. All credit for this research goes to the researchers of this project. Also, feel free to follow us on Twitter and don’t forget to join our 80k+ ML SubReddit.

Recommended Read- LG AI Research Releases NEXUS: An Advanced System Integrating Agent AI System and Data Compliance Standards to Address Legal Concerns in AI Datasets
The post Researchers from UCLA, UC Merced and Adobe propose METAL: A Multi-Agent Framework that Divides the Task of Chart Generation into the Iterative Collaboration among Specialized Agents appeared first on MarkTechPost.

LightThinker: Dynamic Compression of Intermediate Thoughts for More Ef …

Methods like Chain-of-Thought (CoT) prompting have enhanced reasoning by breaking complex problems into sequential sub-steps. More recent advances, such as o1-like thinking modes, introduce capabilities, including trial-and-error, backtracking, correction, and iteration, to improve model performance on difficult problems. However, these improvements come with substantial computational costs. The increased token generation creates significant memory overhead due to the Transformer architecture’s limitations, where attention mechanism complexity grows quadratically with context length, while KV Cache storage increases linearly. For instance, when Qwen32B’s context length reaches 10,000 tokens, the KV Cache consumes memory comparable to the entire model.

Current approaches to accelerate LLM inference fall into three main categories: Quantizing Model, Generating Fewer Tokens, and Reducing KV Cache. The quantizing model involves both parameter and KV Cache quantization techniques. Within the Reducing KV Cache category, pruning-based selection in discrete space and merging-based compression in continuous space emerge as key strategies. Pruning-based strategies implement specific eviction policies to retain only important tokens during inference. Merging-based strategies introduce anchor tokens that compress historically important information. The difference between these two methods is that Pruning-based methods are training-free but require applying eviction policies for every generated token, and Merging-based methods require model training.

Researchers from Zhejiang University, Ant Group, and Zhejiang University – Ant Group Joint Laboratory of Knowledge Graph have proposed LightThinker to enable LLMs to compress intermediate thoughts during reasoning dynamically. Inspired by human cognition, LightThinker compresses verbose reasoning steps into compact representations and discards original reasoning chains, significantly reducing the number of tokens stored in the context window. The researchers also introduce the Dependency (Dep) metric to quantify compression effectiveness by measuring reliance on historical tokens during generation. Moreover, the LightThinker reduces peak memory usage and inference time while maintaining competitive accuracy, offering a promising direction for enhancing LLM efficiency in complex reasoning tasks.

The LightThinker approach is evaluated using the Qwen2.5-7B and Llama3.1-8B models. The researchers conducted full parameter instruction tuning using the Bespoke-Stratos-17k dataset, with the resulting model designated as Vanilla. Five comparison baselines were implemented: two training-free acceleration methods (H2O and SepLLM), one training-based method (AnLLM), and CoT prompting applied to both instruction and R1-Distill models. Evaluation occurred across four datasets (GSM8K, MMLU, GPQA, and BBH), measuring effectiveness and efficiency (via inference time, peak token count, and dependency metrics). The implementation features two compression approaches: token-level compression (converting every 6 tokens into 2) and thought-level compression (using “nn” as a delimiter to segment thoughts).

Evaluation results across the four metrics for both models on all datasets reveal several significant findings. Distill-R1 consistently underperforms compared to CoT across all datasets, with the performance gap attributed to repetition issues caused by Greedy Decoding. H2O effectively preserves model performance while reducing memory usage, validating its greedy eviction policy for long-text generation. However, H2O substantially increases inference time (51% for Qwen and 72% for Llama) due to its token-wise eviction policy creating overhead for each generated token. Moreover, LightThinker matches H2O’s performance with similar compression rates while reducing inference time with a 52% reduction for Qwen and 41% for Llama.

In this paper, researchers introduced LightThinker, a novel approach to enhancing LLM efficiency in complex reasoning tasks through the dynamic compression of intermediate thoughts during generation. By training models to learn optimal timing and methods for compressing verbose reasoning steps into compact representations, LightThinker significantly reduces memory overhead and computational costs while maintaining competitive accuracy. However, several limitations remain: the compatibility with parameter-efficient fine-tuning methods like LoRA or QLoRA is unexplored, the potential benefits of larger training datasets are unknown, and performance degradation is notable on Llama series models when training on small datasets with next-token prediction.

Check out the Paper. All credit for this research goes to the researchers of this project. Also, feel free to follow us on Twitter and don’t forget to join our 80k+ ML SubReddit.

Recommended Read- LG AI Research Releases NEXUS: An Advanced System Integrating Agent AI System and Data Compliance Standards to Address Legal Concerns in AI Datasets
The post LightThinker: Dynamic Compression of Intermediate Thoughts for More Efficient LLM Reasoning appeared first on MarkTechPost.

Self-Rewarding Reasoning in LLMs: Enhancing Autonomous Error Detection …

LLMs have demonstrated strong reasoning capabilities in domains such as mathematics and coding, with models like ChatGPT, Claude, and Gemini gaining widespread attention. The release of GPT -4 has further intensified interest in enhancing reasoning abilities through improved inference techniques. A key challenge in this area is enabling LLMs to detect and correct errors in their outputs—a process known as self-correction. While models can refine responses using external ground-truth reward signals, this approach introduces computational overhead, requiring running multiple models during inference. Studies have shown that accuracy can still improve even when reward feedback is derived from proxy models. However, without external guidance, current LLMs struggle to self-correct based solely on intrinsic reasoning. Recent efforts explore using LLMs as evaluators, where models generate reward signals through instruction-following mechanisms rather than pre-trained reward functions.

Related research on self-rewarding alignment has investigated methods for integrating response generation and evaluation within a single LLM. Iterative fine-tuning approaches enable models to label their outputs, providing learning signals that drive self-improvement. Self-correction studies have demonstrated that while teacher-assisted training enhances reflection in conversational tasks, intrinsic self-correction for reasoning remains unreliable without additional supervision. Most prior work depends on external reward models to determine when corrections should be made, leading to increased inference costs. Rule-based reinforcement learning has also been explored as an alternative, with recent advancements showing that certain pre-trained models naturally exhibit self-correction behaviors. However, replicating these results across different architectures remains challenging, as performance improvements are often linked to proprietary training data and specialized model design.

Researchers from the University of Illinois Urbana-Champaign and the University of Maryland, College Park, explore self-rewarding reasoning in LLMs, enabling them to generate reasoning steps, evaluate their correctness, and refine responses without external feedback. Their two-stage framework first uses sequential rejection sampling to construct long chain-of-thought (CoT) trajectories that embed self-rewarding and self-correction behaviors. Fine-tuning on this data helps models learn these patterns, which are further improved using reinforcement learning with rule-based signals. Experiments with Llama-3 and Qwen-2.5 show that this approach enhances self-correction and matches the performance of models relying on external rewards.

Self-rewarding reasoning in language models is framed as a multi-turn Markov Decision Process (MDP). The model generates an initial response and evaluates its answer. If deemed correct, it stops; otherwise, it refines the response iteratively. This approach follows a two-stage training framework: self-rewarding instruction fine-tuning (IFT) and RL. The IFT stage involves sequential rejection sampling to collect reasoning trajectories, while RL optimizes correctness assessment using KL-regularized training. Unlike traditional RLHF, this method employs oracle rewards to prevent reward hacking. Experiments demonstrate its effectiveness in improving mathematical reasoning accuracy through structured self-correction and verification processes.

The study evaluates mathematical reasoning models using datasets like MATH500, OlympiadBench, and Minerva Math, assessing performance through metrics such as initial and final accuracy, self-correction improvements, and reward model accuracy. Baseline methods like STaR/RAFT and intrinsic self-correction show limited effectiveness, often leading to unnecessary modifications and accuracy drops. In contrast, self-rewarding reasoning models consistently enhance accuracy and correction efficiency while minimizing incorrect changes. Fine-tuning on self-generated corrections significantly improves the model’s ability to refine errors without overcorrection. This approach outperforms traditional methods by integrating self-rewarding signals, leading to more reliable mathematical reasoning capabilities.

In conclusion, the study introduces a self-rewarding reasoning framework for LLMs, improving self-correction and computational efficiency. By integrating self-rewarding IFT and reinforcement learning, the model detects and refines errors using past attempts and internal reward signals. Experiments with Llama-3 and Qwen-2.5 show superior performance over intrinsic self-correction. Future improvements include addressing reward model accuracy issues, enhancing reinforcement learning in later training stages, and exploring multi-turn RL methods. A two-stage approach—sequential rejection sampling for reasoning patterns and reinforcement learning with rule-based signals—enables step-by-step correction without external feedback, offering a scalable, efficient solution for mathematical reasoning.

Check out the Paper and GitHub Page. All credit for this research goes to the researchers of this project. Also, feel free to follow us on Twitter and don’t forget to join our 80k+ ML SubReddit.

Recommended Read- LG AI Research Releases NEXUS: An Advanced System Integrating Agent AI System and Data Compliance Standards to Address Legal Concerns in AI Datasets
The post Self-Rewarding Reasoning in LLMs: Enhancing Autonomous Error Detection and Correction for Mathematical Reasoning appeared first on MarkTechPost.

Streamline work insights with the Amazon Q Business connector for Smar …

Amazon Q Business is a fully managed, generative AI–powered assistant that empowers enterprises to unlock the full potential of their data and organizational knowledge. With Amazon Q Business, you can quickly access answers to questions, generate summaries and content, and complete tasks by using the expertise and information stored across various data sources and enterprise systems within your organization. At the heart of this innovative solution are data source connectors, which seamlessly integrate and index content from multiple data sources and enterprise systems such as SharePoint, Confluence, and Smartsheet.
This post explains how to integrate Smartsheet with Amazon Q Business to use natural language and generative AI capabilities for enhanced insights. Smartsheet, the AI-enhanced enterprise-grade work management platform, helps users manage projects, programs, and processes at scale. By connecting Amazon Q Business with Smartsheet, business users, customer solutions managers, product managers and others can gain deeper understanding into their work by asking natural language questions.
The following are examples of questions you can ask Amazon Q Business to gain actionable insights:

Project status updates – Get quick insights into project health

What’s the status of the website redesign project?
Is the mobile app launch on track for the planned date?
Which projects are currently behind schedule in the Q3 roadmap?

Task management – Find information about tasks and action items

What tasks are assigned to John Doe?
Has the marketing plan been completed?
What’s the due date for the customer research presentation?

Resource allocation – Understand resource distribution and workload

How many resources are allocated to the product launch project?
Which projects require additional staffing based on current task loads?

Budget tracking – Monitor project and departmental budgets in real time

What is the current budget status for the marketing campaign?
How much budget is remaining for the customer service training initiative?

Overview of Smartsheet
Smartsheet combines the simplicity of a spreadsheet with powerful features for collaboration, workflow automation, content management, and reporting. Smartsheet powers mission-critical work securely and reliably at scale for thousands of organizations worldwide, including over 85% of Fortune 500 companies. Customers rely on Smartsheet to open thousands of new restaurant locations, distribute vaccines, build rockets, and more.
In this example, we’re using Smartsheet to track tasks for a software development project. This sheet includes columns for Task, Owner, Team, Stage, Start Date, End Date, and more.

Overview of the Smartsheet connector for Amazon Q Business
By integrating Smartsheet as a data source in Amazon Q Business, you can seamlessly extract insights. For example, service operations managers can use the new connector to deliver complex projects more efficiently and consistently. By asking the Amazon Q Business intelligent assistant specific questions, the team can access insights from multiple data sources, including sheets, conversations, and attachments in Smartsheet that have been connected. The generative AI–powered assistant performs deep searches within the data while respecting access and permission levels, saving valuable time and enhancing project oversight. This streamlined process improves client retention, increases accuracy, and elevates overall service quality.
You can integrate Smartsheet to Amazon Q Business through the AWS Management Console, AWS Command Line Interface (AWS CLI), or the CreateDataSource API.
The Amazon Q Business Smartsheet connector understands user access permissions and strictly enforces them at the time of the query. This makes sure that users can’t access content they don’t have permissions for. For managing security, refer to Identity and access management for Amazon Q Business.
Prerequisites
Before you begin, make sure that you have completed the following prerequisites.

In Smartsheet

Have access to the Smartsheet Event Reporting API. Use the Events API Access Request form to request access for your organization, illustrated by the following screenshot.
A Smartsheet access token. You need this to connect Smartsheet to Amazon Q Business. For generating a token, refer to Authentication and Access Tokens. Keep note of the generated access token because you’ll need to store it in AWS Secrets Manager as part of configuring your Amazon Q application.
In your AWS account

Create an Amazon Q Business application.
Create an Amazon Q Business retriever and add an index.
Create an AWS Identity and Access Management (IAM) role for your data source and, if using the Amazon Q API, note the Amazon Resource Name (ARN) of the IAM role.

For detailed guidance on completing these steps, refer to Prerequisites for connecting Amazon Q Business to Smartsheet.
Configure and prepare the Amazon Q Business Smartsheet connector
Follow the steps below to create the retriever and data source:

Under Enhancements in the navigation pane, select Data sources. Then choose Add an index, as shown in the following screenshot.
Under Index provisioning, select Enterprise and then choose Add an index, as shown in the following screenshot. The Enterprise option is ideal for workloads requiring maximum update performance.
Under Enhancements in the left navigation pane, select Data sources.
On the Data sources page, choose Add data source, as shown in the following screenshot.
On the Add data source page, in the Data sources section, add the Smartsheet data source to your Amazon Q Business application and follow the steps at Connecting Amazon Q Business to Smartsheet using the console.
On the Smartsheet data source page, select and enter the following information:

Data source name
AWS Secrets Manager secret
IAM role and Role name
Sync scope
Frequency

Creating the data source should only take a few minutes. After it’s set up, you’ll notice a green success notification on the console and the data source will be displayed in the Data source details section, as shown in the following screenshot.

Next, you need to sync the Smartsheet data source. In the Sync history section, choose Sync now to initiate the process of crawling and ingesting data from your source into Amazon Q Business. After the sync job is complete, your data source will be fully ready for use, as shown in the following screenshots.

Amazon Q Business and Smartsheet connector in action
After creating your Amazon Q Business application, and successfully syncing the Smartsheet data source, you can test the integration. Ask questions related to a project and observe how the app responds in real time. Follow these steps:

In the left navigation pane, select AmazonQ-smartsheet-connector application and choose Deployed URL, as shown in the following screenshot.

In our example, we asked the following questions regarding our project captured in Smartsheet, and Amazon Q Business generated responses for the project owners regarding status and provided additional information for each task.
Question 1 – What is the project status for creating the UI?
Amazon Q Business response – As shown in the following screenshot, Amazon Q Business generated a response identifying the status as in progress, the name of the team member performing the work, and the scheduled completion date.

Question 2 – List all the projects with their deadlines
Amazon Q Business response – As shown in the following screenshot, Amazon Q Business generated an answer and listed the projects with their deadlines, including citation links from the Smartsheet.

Question 3 – What project is Chloe Evans handling? Can you provide more information about it?
Amazon Q Business response – As shown in the following screenshot, Amazon Q Business generated an answer summarizing the tasks that Chloe Evans is handling.

Troubleshooting
If you encounter issues while asking questions in Amazon Q Business, the problem might be due to missing permissions required to access certain information. Amazon Q Business strictly enforces the document permissions set in its data source. Follow these steps to troubleshoot:

Check indexing status – Confirm whether the Smartsheet connector has been successfully indexed in the Amazon Q Business application. This makes sure that the data source is properly integrated.
Verify user permissions – Make sure that the Smartsheet user account has the necessary permissions to access and read the information from the sheet. Proper permissions are critical for enabling Amazon Q Business to retrieve and process the required data.

Additionally, as an administrator managing the Amazon Q Business application, you can troubleshoot these issues by following these steps and using the document-level sync reports, which enhance visibility into data source sync operations. These reports provide comprehensive and detailed insights integrated into the sync history, including granular indexing status, metadata, and access control list (ACL) details for every document processed during a data source sync job.
The detailed document reports are stored in the new SYNC_RUN_HISTORY_REPORT log stream under the Amazon Q Business application log group, making sure that critical sync job details are available on demand when troubleshooting. For more information, refer to document-level sync reports.
As shown in the following screenshot, we used Amazon CloudWatch Logs Insights to query the SYNC_RUN_HISTORY_REPORT log stream, which meant we could review the sync status in detail.

Clean up
Complete the following steps to clean up your resources:

Select the app you created earlier, then choose Delete.
On the Amazon Q Business console, choose Applications in the navigation pane.
Select the application you created, and on the Actions menu, choose Delete.

Conclusion
In this post, we explored how Amazon Q Business can seamlessly integrate with Smartsheet to help enterprises unlock the full potential of their data and knowledge. With the Smartsheet connector, organizations can empower their teams to find answers quickly, accelerate project tracking, streamline task management, automate workflows, and enhance collaboration.
Now that you’ve learned how to integrate Amazon Q Business with your Smartsheet content, it’s time to tap into the full potential of your organization’s data. To get started, sign up for an Amazon Q Business account and follow the steps in this post to set up the Smartsheet connector. Then, you can start asking Amazon Q Business natural language questions and watch it surface insights in seconds.

About the Authors
Brandon Seiter is a Senior Director, Corporate Development at Smartsheet. He has 15+ years of experience helping companies develop their inorganic growth strategies and overseeing their Corporate Development activities, including mergers & acquisitions, strategic partnerships and new business incubation. At Smartsheet he plays a pivotal role in nurturing relationships with Smartsheet’s technology partners and developing joint partner initiatives.
Aidin Khosrowshahi is an Amazon Q Specialist Solutions Architect at AWS, where he brings his passion for generative AI and serverless applications to life. As an active member of the AI/ML and serverless community, he specializes in Amazon Q Business and Developer solutions while serving as a generative AI expert. He helps customers implement best practices while fostering collaboration and driving innovation across the AI/ML ecosystem.
Chinmayee Rane is a Generative AI Specialist Solutions Architect at AWS, with a core focus on generative AI. She helps Independent Software Vendors (ISVs) accelerate the adoption of generative AI by designing scalable and impactful solutions. With a strong background in applied mathematics and machine learning, she specializes in intelligent document processing and AI-driven innovation. Outside of work, she enjoys salsa and bachata dancing.
Lokesh Chauhan is a Sr. Technical Account Manager at AWS, where he partners with Enterprise Customers to optimize their AWS journey and drive cloud success. He is a member of the AI/ML community and serves as a generative AI expert. As a 12x AWS-certified TAM, he brings deep technical expertise across the AWS platform. Prior to joining AWS, he held leadership positions including Project Lead and Sr. Database admin, building extensive experience in database and operations across multiple organizations.

Level up your problem-solving and strategic thinking skills with Amazo …

Organizations across many industries are harnessing the power of foundation models (FMs) and large language models (LLMs) to build generative AI applications to deliver new customer experiences, boost employee productivity, and drive innovation.
Amazon Bedrock, a fully managed service that offers a choice of high-performing FMs from leading AI companies, provides the easiest way to build and scale generative AI applications with FMs.
Some of the most widely used and successful generative AI use cases on Amazon Bedrock include summarizing documents, answering questions, translating languages, and understanding and generating brand new multimodal content.
Business challenge
Problem-solving, logical reasoning, and critical thinking are critical competencies for achieving business success, accelerating decision-making, and fostering innovation. Although strategy consultants have honed these skills, many knowledge workers lack them due to inadequate training and limited access to appropriate tools. Developing these skills not only enhances individual productivity but also drives significant benefits for the organization.
Business use cases
In this post, we want to demonstrate some additional generative AI use cases on Amazon Bedrock. We show how Anthropic’s Claude 3.5 Sonnet in Amazon Bedrock can be used for a variety of business-related cognitive tasks, such as problem-solving, critical thinking and ideation—to help augment human thinking and improve decision-making among knowledge workers to accelerate innovation. For this, we are using several frameworks and tools widely used by the management consulting community, such as mutually exclusively collectively exhaustive (MECE); strengths, weakness, opportunities, threats (SWOT) analysis, issue tree, value chain analysis and value driver tree analysis.
Solution overview
To demonstrate these five use cases, we used the Amazon Bedrock playground with Anthropic’s Claude Sonnet 3.5 LLM. Where necessary, in addition to text prompts, we also used Anthropic’s Claude Sonnet 3.5’s image-to-text capability to improve the accuracy of the responses generated.
Explanation of the five use cases—together with the prompts and images used to feed the LLM and the responses generated—are shown in the following sections. To improve the explicability of text responses generated by the LLM, we’ve provided additional diagrams, where necessary, to complement each LLM response (for example, the tree diagram corresponding to the LLM generated response).
The following sections explain the solution flow for each use case.
MECE
MECE is a widely used framework for business problem-solving. MECE helps break down a problem into well-defined, nonoverlapping parts (mutually exclusive), but when all the parts are taken together, they’re comprehensive and exhaustive to address the entirety of the problem (collectively exhaustive).
In this example, we want to demonstrate the use of the MECE principle by asking the LLM to arrange food items (in this case, various fried rice options) listed in a restaurant menu, adhering to the MECE guidelines.
We provided the following prompt to the LLM:

Here are some fried rice options: chicken fried rice, vegetable fried rice, lamb fried rice, beef cried rice, egg fried rice, prawn fried rice, squid fried rice
Can you please arrange them using MECE (Mutually Exclusive Collectively Exhaustive) principle?

We get the following response from the LLM:

We arranged the LLM response in tree format for visual clarity, as shown in the following diagram.

Suppose the restaurant wants to add three more varieties to the menu: egg and prawn fried rice, lamb and prawn fried rice, and vegan fried rice. We sought the help of the LLM with the following prompt to rearrange the menu while preserving the MECE principle:

I want to add 3 more varieties to the menu: egg and prawn fried rice, lamb and prawn fried rice, vegan fried rice. Can you please rearrange the list in MECE?

We get the following modified response from the LLM:

 We rearranged the LLM response in tree format for visual clarity. As shown in the following diagram, the LLM has preserved the MECE principle, intelligently adding new categories as needed to accommodate the menu changes.

Issue tree
An issue tree, also known as a logic tree or problem-solving tree, is a strategic analytical tool used to deconstruct complex problems into their constituent elements. This hierarchical framework facilitates a systematic approach to problem-solving by:

Disaggregating the primary issue into discrete, manageable subcomponents
Organizing these elements in a structured, top-down format
Providing comprehensive coverage through the application of the MECE principle

The visual representation afforded by an issue tree enables stakeholders to:

Identify key drivers and root causes
Prioritize areas for further investigation or resource allocation
Maintain a holistic view of the problem while focusing on specific aspects

By employing this methodology, organizations can enhance their decision-making processes, streamline strategic planning, and improve the efficiency of their problem-solving endeavors.
To demonstrate the LLM’s ability to solve problems using an issue tree, we used a fictitious company—AnyCompany Tile Factory—whose profits are down by 30%. AnyCompany’s management wants to use an issue tree to identify the main issues and subordinate issues, and then use it to analyze reasons for declining profits. To give additional context to the LLM, we provided the following diagram with a skeleton issue tree structure.

To prompt the LLM, we attached the preceding diagram and used the following text:

Problem = profits at the AnyCompany Tile Factory is down 30%. Using the diagram as a guide, can you develop an issue tree identifying the main issues, sub issues and then help with the corresponding analysis against each sub-issue to find the reasons for profit decline?

We get the following response from the LLM:

And we populated the issue tree with the response from the LLM for additional visual clarity, as shown in the following diagram.

As shown in the diagram, the LLM has intelligently identified the two main top-level issues contributing to profit decline at AnyCompany (revenue decline and cost increases) and under each category identified the secondary issues, together with a high-level analysis for the management to pursue.
Next, we asked the LLM to elaborate “facility overhead costs” using the prompt:

Please elaborate “facility overhead costs”

We get the following response from the LLM:

SWOT
A SWOT analysis is a strategic management tool that can be used to evaluate the strengths, weaknesses, opportunities, and threats of an organization, industry, or project. SWOT helps in decision-making and strategy formulation by identifying internal factors (strengths and weaknesses) and external factors (opportunities and threats) that can impact success. Management can then use the analysis to develop way forward strategies, using strengths, addressing weaknesses, capitalizing on opportunities, and mitigating threats, as identified in the SWOT.
In this example, we ask the LLM to develop a way forward strategy for the Australian higher education sector using the SWOT analysis diagram provided. We ask it to identify four key strategic themes for the sector, making sure the approach uses inherent strengths, addresses weaknesses, capitalizes on opportunities, and mitigates threats, as identified in the SWOT diagram and illustrated in the following graphic. We also ask the LLM to list critical activities to be pursued by the sector under each strategic theme.

To prompt the LLM, we attached the preceding diagram and used the following text:

Using the SWOT analysis for the Australian higher education sector, we want your expertise to help develop the way forward strategy. Please identify 4 key strategic themes for the sector, ensuring your approach leverages strengths, addresses weaknesses, capitalizes on opportunities, mitigates threats as identified in the SWOT diagram. Under each strategic theme, list critical activities to be pursued.

We get the following response from the LLM, which includes four strategic themes and activities to be pursued:

We constructed the following diagram based on the LLM response for visual clarity.

Value chain analysis
Value chain analysis is a strategic management tool that helps organizations evaluate each value-creating activity in their value chain, such as inbound logistics or operations, to identify opportunities to build completive advantage, reduce costs, and increase efficiencies.
In this example, we want the LLM to perform a value chain analysis for the AnyCompany Tile Factory and make recommendations to improve profitability. As additional context to the LLM, we provided the following end-to-end value chain diagram for AnyCompany.

To prompt the LLM, we used the following text:

Profits at the AnyCompany Tile Factory are down 30%. The diagram shows their end-to-end value chain. Please perform a value chain analysis and make recommendations to improve profitability at AnyCompany.

We get the following response from the LLM, with recommendations for improving profitability across the five main areas:

We updated the value chain diagram with the recommendations supplied by the LLM under each category, as shown in the following diagram.

Value driver tree
A value driver tree is a framework that maps out key factors influencing an organization’s value or specific metrics such as revenue, profit, or customer satisfaction. This framework breaks down high-level business objectives and drivers into smaller, measurable components. By doing so, it reveals the cause-and-effect relationships between these elements, providing insights into how various factors contribute to overall business performance. Value driver trees are used for business performance improvement, strategic planning, and decision-making.
In this example, we want the LLM to define a value driver tree for the AnyCompany Tile Factory so the management team can analyze revenue, cost, and efficiency drivers contributing to low profitability and take action to remediate issues.
To prompt the LLM we used the following:

Profits at the AnyCompany Tile Factory are down 30%. Please help develop a value driver tree for the AnyCompany’s management to analyze the problem and take remedial action. Consider revenue, cost and efficiency drivers

We get the following response from the LLM, with a breakdown of major components—revenue, costs, and efficiency— affecting profitability at AnyCompany. It has also provided a five-step action plan for the management to consider.

We constructed the following value driver diagram for AnyCompany Tile Factory in tree format, based on the responses provided by the LLM.

Conclusion
Problem-solving, critical thinking, and logical reasoning are cognitive processes that use the brain to find a solution to a problem or reach an end goal, especially when the answer isn’t immediately obvious. As we’ve shown in the examples in this post, LLMs such as Anthropic’s Claude 3.5 Sonnet on Amazon Bedrock can be used to improve your cognitive skills, especially in the areas of problem-solving, creative thinking, and ideation. This in turn will help improve team collaboration, cut decision times, and drive innovation. The examples we used are basic to showcase the art of the possible.  To improve LLM responses in complex problem-solving use cases, we recommend using RAG sources that are relevant to the problem, chain-of-thought prompting, and giving additional problem-specific context through prompt engineering.
We encourage you to begin exploring these capabilities through the Amazon Bedrock chat playground, a tool in the AWS Management Console that provides a visual interface to experiment with running inference on different LLMs and using different configurations.

About the Authors
Senaka Ariyasinghe is a Senior Partner Solutions Architect working with Global Systems Integrators at Amazon Web Services (AWS). In his role, Senaka guides AWS Partners in the APJ region to design and scale well-architected solutions, focusing on generative AI, machine learning, cloud migrations, and application modernization initiatives.
Deependra Shekhawat is a Senior Energy and Utilities Industry Specialist Solutions Architect based in Sydney, Australia. In his role, Deependra helps energy companies across the APJ region use cloud technologies to drive sustainability and operational efficiency. He specializes in creating robust data foundations and advanced workflows that enable organizations to harness the power of big data, analytics, and machine learning for solving critical industry challenges.

Optimizing AI implementation costs with Automat-it

This post was written by Claudiu Bota, Oleg Yurchenko, and Vladyslav Melnyk of AWS Partner Automat-it.
As organizations adopt AI and machine learning (ML), they’re using these technologies to improve processes and enhance products. AI use cases include video analytics, market predictions, fraud detection, and natural language processing, all relying on models that analyze data efficiently. Although models achieve impressive accuracy with little latency, they often demand computational resources with significant computing power, including GPUs, to run inferences. Therefore, maintaining the right balance between performance and cost is essential, especially when deploying models at scale.
One of our customers encountered this exact challenge. To address this issue, they engaged Automat-it, an AWS Premier Tier Partner, to design and implement their platform on AWS, specifically using Elastic Kubernetes Service (Amazon EKS). Automat-it specializes in helping startups and scaleups grow through hands-on cloud DevOps, MLOps and FinOps services. The collaboration aimed to achieve scalability and performance while optimizing costs. Their platform requires highly accurate models with low latency, and the costs for such demanding tasks escalate quickly without proper optimization.
In this post, we explain how Automat-it helped this customer achieve a more than twelvefold cost savings while keeping AI model performance within the required performance thresholds. This was accomplished through careful tuning of architecture, algorithm selection, and infrastructure management.
Customer challenge
Our customer specializes in developing AI models for video intelligence solutions using YOLOv8 and the Ultralytics library. An end-to-end YoloV8 deployment consists of three stages:

Preprocessing – Prepares raw video frames through resizing, normalization, and format conversion
Inference – In which the YOLOv8 model generates predictions by detecting and classifying objects in the curated video frames
Postprocessing – In which predictions are refined using techniques such as non-maximum suppression (NMS), filtering, and output formatting.

They provide their clients with models that analyze live video streams and extract valuable insights from the captured frames, each customized to a specific use case. Initially, the solution required each model to run on a dedicated GPU at runtime, needing GPU instances per customer. This setup led to underutilized GPU resources and elevated operational costs.
Therefore, our primary objective was to optimize GPU utilization while lowering overall platform costs and keeping data processing time as minimal as possible. Specifically, we aimed to limit AWS infrastructure costs to $30 per camera per month while keeping the total processing time (preprocessing, inference, and postprocessing) under 500 milliseconds. Achieving these savings without lowering the model performance—particularly by maintaining low inference latency—remains essential to providing the desired level of service for each customer.
Initial approach
Our initial approach followed a client-server architecture, splitting the YOLOv8 end-to-end deployment into two components. The client component, running on CPU instances, handled the preprocessing and postprocessing stages. Meanwhile, the server component, running on GPU instances, was dedicated to inference and responded to requests from the client. This functionality was implemented using a custom gRPC wrapper, providing efficient communication between the components.
The goal of this approach was to reduce costs by using GPUs exclusively for the inference stage rather than for the entire end-to-end deployment. Additionally, we assumed that client-server communication latency would have a minimal impact on the overall inference time. To assess the effectiveness of this architecture, we conducted performance tests using the following baseline parameters:

Inference was performed on g4dn.xlarge GPU-based instances because the customer’s models were optimized to run on T4 GPUs NVIDIA
Customer’s models used the YOLOv8n model with Ultralytics version 8.2.71

The results were evaluated based on the following key performance indicators (KPIs):

Preprocessing time – The amount of time required to prepare the input data for the model
Inference time – The duration taken by the YoloV8 model to process the input and produce results
Postprocessing time – The time needed to finalize and format the model’s output for use
Network communication time – The duration of communication between the client component running on CPU instances and the server component running on GPU instances
Total time – The overall duration from when an image is sent to the YoloV8 model until results are received, including all processing stages

The findings were as follows:

Preprocess (ms)
Inference (ms)
Postprocess (ms)
Network communication (ms)
Total (ms)

Custom gRPC
2.7
7.9
1.1
10.26
21.96

The GPU-based instance completed inference in 7.9 ms. However, the network communication overhead of 10.26 ms increased the total processing time. Although the total processing time was acceptable, each model required a dedicated GPU-based instance to run, resulting in unacceptable costs for the customer. Specifically, the inference cost per camera was $353.03 monthly, exceeding the customer’s budget.
Finding a better solution
Although the performance results were promising, even with the added latency from network communication, costs per camera were still too high, so our solution needed further optimization. Additionally, the custom gRPC wrapper lacked an automatic scaling mechanism to accommodate the addition of new models and required ongoing maintenance, adding to its operational complexity.
To address these challenges, we moved away from the client-server approach and implemented GPU time-slicing (fractionalization), which involves dividing GPU access into discrete time intervals. This approach allows AI models to share a single GPU, each utilizing a virtual GPU during its assigned slice. It’s similar to CPU time-slicing between processes, optimizing resource allocation without lowering the performance. This approach was inspired by several AWS blog posts that can be found in the references section.
We implemented GPU time-slicing in the EKS cluster by using the NVIDIA Kubernetes device plugin. This equipped us to use Kubernetes’s native scaling mechanisms, simplifying the scaling process to accommodate new models and reducing operational overhead. Moreover, by relying on the plugin, we avoided the need to maintain custom code, streamlining both implementation and long-term maintenance.
In this configuration, the GPU instance was set to split into 60 time-sliced virtual GPUs. We used the same KPIs as in the previous setup to measure efficiency and performance under these optimized conditions, making sure that cost reduction aligned with our service quality benchmarks.
We conducted the tests in three stages, as described in the following sections.
Stage 1
In this stage, we ran one pod on a g4dn.xlarge GPU-based instance. Each pod runs the three phases of the end-to-end YOLOv8 deployment on the GPU and processes video frames from a single camera. The findings are shown in the following graph and table.

Preprocess (ms)
Inference (ms)
Postprocess (ms)
Total (ms)

1 pod
2
7.8
1
10.8

We successfully achieved an inference time of 7.8 ms and a total processing time of 10.8 ms, which aligned with the project’s requirements. The GPU memory usage for a single pod was 247MiB, and the GPU processor utilization was 12%. The memory usage per pod indicated we could run approximately 60 processes (or pods) on a 16GiB GPU.
Stage 2
In this stage, we ran 20 pods on a g4dn.2xlarge GPU-based instance. We changed the instance type from g4dn.xlarge to g4dn.2xlarge due to CPU overload associated with data processing and loading. The findings are shown in the following graph and table.

Preprocess (ms)
Inference (ms)
Postprocess (ms)
Total (ms)

20 pods
11
42
55
108

At this stage, GPU memory usage reached 7,244 MiB, with GPU processor utilization peaking between 95% and 99%. A total of 20 pods utilized half of the GPU’s 16 GiB memory and fully consumed the GPU processor, leading to increased processing times. Although both inference and total processing times rose, this outcome was anticipated and deemed acceptable. The next objective was determining the maximum number of pods the GPU could support on its memory capacity.
Stage 3
At this stage, we aimed to run 60 pods on a g4dn.2xlarge GPU-based instance. Subsequently, we changed the instance type from g4dn.2xlarge to g4dn.4xlarge and then to g4dn.8xlarge.
The goal was to maximize GPU memory utilization. However, data processing and loading overloaded the instance’s CPU. This prompted us to switch to instances that still had one GPU but offered more CPUs.
The findings are shown in the following graph and table.

Preprocess (ms)
Inference (ms)
Postprocess (ms)
Total (ms)

54 pods
21
56
128
205

The GPU memory usage was 14780MiB, and the GPU processor utilization was 99–100%. Despite these adjustments, we encountered GPU out-of-memory errors that prevented us from scheduling all 60 pods. Ultimately, we could accommodate 54 pods, representing the maximum number of AI models that could fit on a single GPU.
In this scenario, the inference costs per camera associated with GPU usage were $27.81 per month per camera, a twelvefold reduction compared to the initial approach. By adopting this approach, we successfully met the customer’s cost requirements per camera per month while maintaining acceptable performance levels.
Conclusion
In this post, we explored how Automat-it helped one of our customers achieve a twelvefold cost reduction while maintaining the performance of their YOLOV8-based AI models within acceptable ranges. The test results demonstrate that GPU time-slicing enables the maximum number of AI models to operate efficiently on a single GPU, significantly reducing costs while providing high performance. Furthermore, this method necessitates minimal maintenance and modifications to the model code, enhancing scalability and ease of use.
References
To learn more, refer to the following resources:
AWS

GPU sharing on Amazon EKS with NVIDIA time-slicing and accelerated EC2 instances
Delivering video content with fractional GPUs in containers on Amazon EKS

Community

Time-Slicing GPUs in Kubernetes

Disclaimer
The content and opinions in this post are those of the third-party author and AWS is not responsible for the content or accuracy of this post.

About the authors
Claudiu Bota is a Senior Solutions Architect at Automat-it, helping customers across the entire EMEA region migrate to AWS and optimize their workloads. He specializes in containers, serverless technologies, and microservices, focusing on building scalable and efficient cloud solutions. Outside of work, Claudiu enjoys reading, traveling, and playing chess.
Oleg Yurchenko is the DevOps Director at Automat-it, where he spearheads the company’s expertise in DevOps best practices and solutions. His focus areas include containers, Kubernetes, serverless, Infrastructure as Code, and CI/CD. With over 20 years of hands-on experience in system administration, DevOps, and cloud technologies, Oleg is a passionate advocate for his customers, guiding them in building modern, scalable, and cost-effective cloud solutions.
Vladyslav Melnyk is a Senior MLOps Engineer at Automat-it. He is a Seasoned Deep Learning enthusiast with a passion for Artificial Intelligence, taking care of AI products through their lifecycle, from experimentation to production. With over 9 years of experience in AI within AWS environments, he is also a big fan of leveraging cool open-source tools. Result-oriented and ambitious, with a strong focus on MLOps, Vladyslav ensures smooth transitions and efficient model deployment. He is skilled in delivering deep learning models, always learning and adapting to stay ahead in the field.