<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Hassan Sherwani</title>
    <description>The latest articles on DEV Community by Hassan Sherwani (@hassan_sherwani_9dd766c43).</description>
    <link>https://dev.to/hassan_sherwani_9dd766c43</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2253152%2F708e27ca-867a-4799-a05d-5f5e89500c73.jpg</url>
      <title>DEV Community: Hassan Sherwani</title>
      <link>https://dev.to/hassan_sherwani_9dd766c43</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/hassan_sherwani_9dd766c43"/>
    <language>en</language>
    <item>
      <title>Building Serverless Agentic Workflows with Amazon Bedrock</title>
      <dc:creator>Hassan Sherwani</dc:creator>
      <pubDate>Sat, 30 Nov 2024 02:15:21 +0000</pubDate>
      <link>https://dev.to/hassan_sherwani_9dd766c43/building-serverless-agentic-workflows-with-amazon-bedrock-1j6h</link>
      <guid>https://dev.to/hassan_sherwani_9dd766c43/building-serverless-agentic-workflows-with-amazon-bedrock-1j6h</guid>
      <description>&lt;p&gt;In the rapidly evolving landscape of AI-driven automation, serverless computing stands as a transformative force, enabling developers to craft scalable and efficient applications without the constraints of managing infrastructure. Amazon Bedrock, a fully managed service from AWS, unlocks the potential of serverless computing&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft7owcsx977cm1vyl257t.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft7owcsx977cm1vyl257t.jpg" alt="Image description" width="300" height="168"&gt;&lt;/a&gt; and advanced AI models, empowering the creation of intelligent workflows led by AI agents. In this blog, we will delve into the course on Serverless Agentic Workflows with Amazon Bedrock and share coding examples to inspire your journey.&lt;/p&gt;
&lt;h1&gt;
  
  
  What is Amazon Bedrock?
&lt;/h1&gt;

&lt;p&gt;Unlock the potential of Amazon Bedrock, a fully managed service that connects developers to a diverse range of foundation models (FMs) from top AI providers like AI21 Labs, Anthropic, Stability AI, and Amazon Titan. Thanks to its serverless environment, Bedrock allows you to effortlessly build and scale AI-driven applications without the hassle of infrastructure management. Focus on innovation and creativity while Bedrock takes care of the technical complexities.&lt;/p&gt;

&lt;p&gt;Enhance your workflows with Serverless Agentic workflow, allowing you to automate intricate tasks using intelligent AI agents. These versatile agents can seamlessly interact with external systems, make informed decisions, invoke APIs, and pull data when necessary. Experience the future of productivity by harnessing the power of AI to elevate your projects.&lt;/p&gt;
&lt;h1&gt;
  
  
  Key Concepts from the Course
&lt;/h1&gt;

&lt;p&gt;The course "Serverless Agentic Workflows with Amazon Bedrock" focuses on building intelligent workflows using Amazon Bedrock. Here are the main lessons covered in the course:&lt;/p&gt;
&lt;h3&gt;
  
  
  Creating Your First Serverless Agent:
&lt;/h3&gt;

&lt;p&gt;Learn to initialize an AI agent and integrate it with your workflows.&lt;/p&gt;
&lt;h3&gt;
  
  
  Connecting to External Services:
&lt;/h3&gt;

&lt;p&gt;Make the agent interact with real-world systems, such as CRMs or databases.&lt;/p&gt;
&lt;h3&gt;
  
  
  Equipping the Agent with a Code Interpreter:
&lt;/h3&gt;

&lt;p&gt;Enable the agent to perform complex calculations and make data-driven decisions.&lt;/p&gt;
&lt;h3&gt;
  
  
  Implementing Guardrails:
&lt;/h3&gt;

&lt;p&gt;Add security and ethical guardrails to control the agent’s behavior.&lt;/p&gt;
&lt;h3&gt;
  
  
  Connecting to Support Documents:
&lt;/h3&gt;

&lt;p&gt;Use Retrieval-Augmented Generation (RAG) to allow your agent to query documents and resolve issues autonomously.&lt;br&gt;
Let’s break down these lessons with coding examples!&lt;/p&gt;
&lt;h2&gt;
  
  
  1. Creating Your First Serverless Agent
&lt;/h2&gt;

&lt;p&gt;In this section, we’ll initialize an AI agent using Amazon Bedrock. The agent can be used to handle tasks like customer support, product recommendation, or simple Q&amp;amp;A.&lt;/p&gt;

&lt;p&gt;Here’s how you can set up your first serverless agent;&lt;/p&gt;
&lt;h3&gt;
  
  
  Prerequisites
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;AWS account&lt;/li&gt;
&lt;li&gt;Amazon Bedrock service access&lt;/li&gt;
&lt;li&gt;Basic knowledge of Python
Let's initialize an AI Agent
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import boto3

# Initialize the Amazon Bedrock client
client = boto3.client('bedrock')

# Set up the parameters for the agent
parameters = {
    'modelId': 'AmazonTitan',
    'input': 'Hello, how can I assist you today?'
}

# Call the model to initialize the agent
response = client.invoke_model(**parameters)

# Output the agent's response
print(response['output'])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;This code effectively initializes an Amazon Titan model by utilizing the invoke_model function. It sends a straightforward query: "Hello, how can I assist you today?" The printed response from the agent illustrates its capability to generate dynamic and relevant answers, which showcases the model's potential for providing useful interactions.&lt;/p&gt;
&lt;h2&gt;
  
  
  2. Connecting to External Services
&lt;/h2&gt;

&lt;p&gt;To make the AI agent more powerful, we can integrate it with external services like a CRM or ticketing system. For example, we can connect to a database to fetch customer records.&lt;/p&gt;

&lt;p&gt;Fetching Data from a Database&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import boto3

# Set up DynamoDB client
dynamodb = boto3.client('dynamodb')

def fetch_customer_info(customer_id):
    response = dynamodb.get_item(
        TableName='CustomerRecords',
        Key={'customer_id': {'S': customer_id}}
    )
    return response.get('Item', {})

# Fetch customer info
customer_id = '12345'
customer_info = fetch_customer_info(customer_id)

print(customer_info)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the code connects to a DynamoDB table called CustomerRecords and fetches information for a specific customer. This integration allows the agent to retrieve and use real-time customer data to make informed decisions.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Equipping the Agent with a Code Interpreter
&lt;/h2&gt;

&lt;p&gt;The agent can be equipped to execute code or perform calculations, which helps it make data-driven decisions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Initialize the Bedrock client
client = boto3.client('bedrock')

# Code for calculating product prices
def calculate_price(base_price, discount):
    return base_price - (base_price * discount / 100)

# Implement logic with agent
def agent_with_code_interpreter():
    base_price = 100  # Sample base price
    discount = 10     # Sample discount percentage
    final_price = calculate_price(base_price, discount)
    return f"The final price after a {discount}% discount is: ${final_price}"

# Call the agent
response = client.invoke_model(
    modelId='AmazonTitan',
    input=agent_with_code_interpreter()
)

print(response['output'])

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the agent performs a simple price calculation, reducing a base price by a specified discount percentage. This demonstrates how agents can use custom code logic to enhance their decision-making ability.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Implementing Guardrails
&lt;/h2&gt;

&lt;p&gt;Guardrails ensure that the AI agent behaves responsibly. For example, you can add logic to prevent the agent from revealing sensitive information or making unethical decisions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def guardrails(agent_output):
    prohibited_keywords = ['password', 'credit card']
    for keyword in prohibited_keywords:
        if keyword in agent_output:
            return "Sorry, I cannot provide that information."
    return agent_output

# Example agent output
agent_output = "Here is your password: 12345"

# Apply guardrails
safe_output = guardrails(agent_output)
print(safe_output)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code, the agent’s output is filtered for sensitive information like passwords. If any such information is detected, the agent responds with a safe message.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Connecting to Support Documents with Retrieval-Augmented Generation (RAG)
&lt;/h2&gt;

&lt;p&gt;Using RAG, your agent can query a database of support documents to retrieve the most relevant information when a customer asks a question.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Initialize the Bedrock client
client = boto3.client('bedrock')

# Define a function to query support documents
def query_support_documents(query):
    response = client.retrieve_documents(
        query=query,
        document_store='SupportDocsStore'
    )
    return response['documents'][0]  # Return the first relevant document

# Query the support documents
query = "How do I reset my password?"
document = query_support_documents(query)

print(document)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code, the agent queries a document store (e.g., a collection of FAQ articles) to find the best document that answers the user's question about resetting a password.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;This blog discusses building a Serverless Agentic workflow with Amazon Bedrock. We highlight key course lessons and provide coding examples showing how AI agents can interact with external services, perform calculations, and retrieve information. Amazon Bedrock combines serverless architecture with AI models, making creating scalable applications for customer support and document processing easier.&lt;/p&gt;

&lt;p&gt;For those wanting to learn more, the Serverless Agentic Workflows with Amazon Bedrock course offers a step-by-step guide on creating and managing these workflows. It covers automating customer interactions, integrating with external services, and establishing ethical guidelines for AI agents.&lt;/p&gt;

&lt;p&gt;References:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Serverless Agentic Workflows with Amazon Bedrock Course: &lt;a href="https://learn.deeplearning.ai/courses/serverless-agentic-workflows-with-amazon-bedrock/lesson/1/introduction" rel="noopener noreferrer"&gt;https://learn.deeplearning.ai/courses/serverless-agentic-workflows-with-amazon-bedrock/lesson/1/introduction&lt;/a&gt;.
-Amazon bedrock agents: &lt;a href="https://aws.amazon.com/bedrock/agents/" rel="noopener noreferrer"&gt;https://aws.amazon.com/bedrock/agents/&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>genai</category>
      <category>agenticai</category>
      <category>aws</category>
      <category>amazonbedrock</category>
    </item>
    <item>
      <title>Harnessing Multi-Agent Systems with CrewAI: Concepts, Coding, and Real-World Applications</title>
      <dc:creator>Hassan Sherwani</dc:creator>
      <pubDate>Sat, 23 Nov 2024 04:16:56 +0000</pubDate>
      <link>https://dev.to/hassan_sherwani_9dd766c43/harnessing-multi-agent-systems-with-crewai-concepts-coding-and-real-world-applications-1kib</link>
      <guid>https://dev.to/hassan_sherwani_9dd766c43/harnessing-multi-agent-systems-with-crewai-concepts-coding-and-real-world-applications-1kib</guid>
      <description>&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;In the exciting world of AI and automation, Multi-Agent Systems (MAS) are making a big impact by spreading tasks among smart agents. These systems offer great benefits like scalability, teamwork, and efficiency, helping us tackle complex problems in various fields. In this blog, we’ll dive into the basics of multi-agent systems, highlight the amazing features of CrewAI, and chat about how these ideas can be used in areas like health insurance, finance, human resources, and real estate. Let’s explore together!&lt;/p&gt;

&lt;h1&gt;
  
  
  The Concept of Multi-Agent Systems
&lt;/h1&gt;

&lt;p&gt;A Multi-Agent System (MAS) consists of multiple autonomous entities called agents, which collaborate or compete to achieve a common goal. These systems are inspired by distributed problem-solving and emulate human teamwork by dividing large tasks into manageable subtasks.&lt;/p&gt;

&lt;h1&gt;
  
  
  Key Characteristics of MAS
&lt;/h1&gt;

&lt;h3&gt;
  
  
  Autonomy:
&lt;/h3&gt;

&lt;p&gt;Each agent operates independently, making decisions without external intervention.&lt;/p&gt;

&lt;h3&gt;
  
  
  Communication:
&lt;/h3&gt;

&lt;p&gt;Agents share data or task progress through defined protocols.&lt;/p&gt;

&lt;h3&gt;
  
  
  Collaboration:
&lt;/h3&gt;

&lt;p&gt;Agents coordinate their actions to fulfill a common objective.&lt;/p&gt;

&lt;h3&gt;
  
  
  Adaptability:
&lt;/h3&gt;

&lt;p&gt;MAS can adjust to dynamic environments and task requirements.&lt;/p&gt;

&lt;h1&gt;
  
  
  Advantages of MAS
&lt;/h1&gt;

&lt;h3&gt;
  
  
  Scalability:
&lt;/h3&gt;

&lt;p&gt;Tasks are distributed across agents, reducing bottlenecks.&lt;/p&gt;

&lt;h3&gt;
  
  
  Modularity:
&lt;/h3&gt;

&lt;p&gt;Agents can be added, removed, or replaced without impacting the system's functionality.&lt;/p&gt;

&lt;h3&gt;
  
  
  Efficiency:
&lt;/h3&gt;

&lt;p&gt;Parallel execution of subtasks optimizes resource usage.&lt;/p&gt;

&lt;h1&gt;
  
  
  Examples in Action
&lt;/h1&gt;

&lt;p&gt;In logistics, MAS can optimize delivery routes by assigning tasks to delivery agents.&lt;br&gt;
In robotics, teams of autonomous robots collaborate to assemble complex machinery.&lt;/p&gt;
&lt;h1&gt;
  
  
  What is CrewAI?
&lt;/h1&gt;

&lt;p&gt;CrewAI is a powerful Python-based framework that streamlines the creation and execution of multi-agent systems. It empowers developers to define agents, assign tasks, and orchestrate their interactions within a crew with ease. By harnessing the capabilities of large language models (LLMs) like GPT-3.5 and GPT-4, CrewAI delivers unparalleled efficiency and effectiveness in managing complex systems.&lt;/p&gt;
&lt;h1&gt;
  
  
  Key Components of CrewAI
&lt;/h1&gt;
&lt;h3&gt;
  
  
  Agents:
&lt;/h3&gt;

&lt;p&gt;Autonomous entities with defined roles, goals, and tools.&lt;/p&gt;
&lt;h3&gt;
  
  
  Tasks:
&lt;/h3&gt;

&lt;p&gt;Descriptions of specific objectives assigned to agents.&lt;/p&gt;
&lt;h3&gt;
  
  
  Crew:
&lt;/h3&gt;

&lt;p&gt;The orchestrator that binds agents and tasks, enabling collaborative execution.&lt;/p&gt;
&lt;h1&gt;
  
  
  Technical Implementation of MAS using CrewAI
&lt;/h1&gt;

&lt;p&gt;Let’s dive into the process of building a CrewAI-powered MAS for tailoring job applications, as demonstrated in the provided notebook.&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 1: Define the Agents
&lt;/h3&gt;

&lt;p&gt;Each agent is designed to handle a specific part of the process.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from crewai import Agent

# Researcher Agent
researcher = Agent(
    role="Tech Job Researcher",
    goal="Analyze job postings to extract key qualifications and skills.",
    tools=[scrape_tool, search_tool],
    verbose=True,
    backstory="Expert in identifying job requirements."
)

# Profiler Agent
profiler = Agent(
    role="Personal Profiler for Engineers",
    goal="Compile detailed applicant profiles.",
    tools=[scrape_tool, search_tool, read_resume, semantic_search_resume],
    verbose=True,
    backstory="Skilled in creating comprehensive profiles from diverse data."
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 2: Define the Tasks
&lt;/h3&gt;

&lt;p&gt;Tasks specify what each agent must accomplish.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from crewai import Task

# Research Task
research_task = Task(
    description="Analyze job postings to extract required skills.",
    expected_output="A structured list of job requirements.",
    agent=researcher,
    async_execution=True
)

# Profile Task
profile_task = Task(
    description="Create a detailed profile using applicant information.",
    expected_output="A comprehensive professional profile document.",
    agent=profiler,
    async_execution=True
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 3: Create the Crew
&lt;/h3&gt;

&lt;p&gt;Combine agents and tasks into a cohesive crew.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from crewai import Crew

job_application_crew = Crew(
    agents=[researcher, profiler],
    tasks=[research_task, profile_task],
    verbose=True
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 4: Execute the Crew
&lt;/h3&gt;

&lt;p&gt;Provide inputs and initiate the workflow.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
inputs = {
    'job_posting_url': 'https://example.com/job-posting',
    'github_url': 'https://github.com/user',
    'personal_writeup': "An experienced software engineer with expertise in AI."
}

result = job_application_crew.kickoff(inputs=inputs)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Case Studies/ Application in Real World
&lt;/h1&gt;

&lt;h2&gt;
  
  
  1. Health Insurance
&lt;/h2&gt;

&lt;p&gt;Problem: Automating claim approvals with MAS.&lt;/p&gt;

&lt;p&gt;Agents:&lt;br&gt;
Claim Validator: Verifies the authenticity of claims using insurance databases.&lt;br&gt;
Medical Expert: Assesses the relevance of diagnoses.&lt;br&gt;
Fraud Detector: Identifies fraudulent claims using anomaly detection.&lt;br&gt;
Workflow:&lt;br&gt;
Extract claim details.&lt;br&gt;
Validate against policy documents.&lt;br&gt;
Approve or flag claims for manual review.&lt;br&gt;
Outcome: Faster claim processing and reduced fraud.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Finance
&lt;/h2&gt;

&lt;p&gt;Problem: Portfolio optimization for investment clients.&lt;/p&gt;

&lt;p&gt;Agents:&lt;br&gt;
Market Analyst: Monitors real-time market data.&lt;br&gt;
Risk Assessor: Evaluates portfolio risks.&lt;br&gt;
Investment Strategist: Recommends asset allocations.&lt;br&gt;
Workflow:&lt;br&gt;
Collect client preferences and financial goals.&lt;br&gt;
Generate optimal portfolios using agent collaboration.&lt;br&gt;
Provide actionable insights to clients.&lt;br&gt;
Outcome: Improved investment returns and client satisfaction.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Human Resources
&lt;/h2&gt;

&lt;p&gt;Problem: Streamlining candidate selection.&lt;/p&gt;

&lt;p&gt;Agents:&lt;br&gt;
Job Matcher: Analyzes resumes against job descriptions.&lt;br&gt;
Interviewer: Generates targeted interview questions.&lt;br&gt;
Skill Evaluator: Assesses candidate skills through semantic search.&lt;br&gt;
Workflow:&lt;br&gt;
Parse and analyze candidate resumes.&lt;br&gt;
Generate evaluation reports.&lt;br&gt;
Assist interviewers with data-driven insights.&lt;br&gt;
Outcome: Enhanced recruitment efficiency.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Real Estate
&lt;/h2&gt;

&lt;p&gt;Problem: Personalized property recommendations.&lt;/p&gt;

&lt;p&gt;Agents:&lt;br&gt;
Market Researcher: Gathers property listings.&lt;br&gt;
Buyer Profiler: Analyzes buyer preferences.&lt;br&gt;
Price Evaluator: Predicts property prices using historical data.&lt;br&gt;
Workflow:&lt;br&gt;
Collect buyer requirements.&lt;br&gt;
Match properties based on preferences.&lt;br&gt;
Provide a ranked list of suitable properties.&lt;br&gt;
Outcome: Accelerated property discovery.&lt;/p&gt;

&lt;h1&gt;
  
  
  Future of MAS and CrewAI
&lt;/h1&gt;

&lt;p&gt;The flexibility and modularity of Multi-Agent Systems (MAS) provide exciting opportunities for diverse applications across various fields. By utilizing tools like CrewAI, developers can efficiently prototype and deploy intelligent systems, fostering innovation. Looking ahead, the integration of advanced technologies such as reinforcement learning, the Internet of Things (IoT), and blockchain can significantly expand the capabilities of MAS, paving the way for more powerful and effective solutions.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;Multi-Agent Systems (MAS), powered by CrewAI, deliver unmatched efficiency in task automation and problem-solving. By mastering the underlying theory and harnessing it creatively, we have the potential to revolutionize industries such as healthcare and real estate. Our compelling case studies prove that MAS is not just an abstract idea; it is an effective, practical solution to real-world challenges.&lt;/p&gt;

&lt;p&gt;CrewAI is just one powerful tool in our arsenal. In our upcoming blogs, we will confidently explore a variety of exciting options, including Lang-graph, Autogen, AWS's built-in agent, and more. Stay tuned for insights that will elevate your understanding!&lt;/p&gt;

&lt;h1&gt;
  
  
  References
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;CrewAI : &lt;a href="https://learn.crewai.com/%5C" rel="noopener noreferrer"&gt;https://learn.crewai.com/\&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;CrewAI Github: &lt;a href="https://github.com/crewAIInc/crewAI" rel="noopener noreferrer"&gt;https://github.com/crewAIInc/crewAI&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>agenticai</category>
      <category>multiagentsystems</category>
      <category>crewai</category>
      <category>genai</category>
    </item>
    <item>
      <title>Exploring the Exciting Possibilities of NVIDIA Megatron LM: A Fun and Friendly Code Walkthrough with PyTorch &amp; NVIDIA Apex!</title>
      <dc:creator>Hassan Sherwani</dc:creator>
      <pubDate>Sat, 26 Oct 2024 00:50:53 +0000</pubDate>
      <link>https://dev.to/hassan_sherwani_9dd766c43/exploring-the-exciting-possibilities-of-nvidia-megatron-lm-a-fun-and-friendly-code-walkthrough-with-pytorch-nvidia-apex-n3d</link>
      <guid>https://dev.to/hassan_sherwani_9dd766c43/exploring-the-exciting-possibilities-of-nvidia-megatron-lm-a-fun-and-friendly-code-walkthrough-with-pytorch-nvidia-apex-n3d</guid>
      <description>&lt;p&gt;In the extensive realm of GenAI, large language models (LLMs) have captured remarkable attention for their capacity to execute tasks such as text generation, translation, and even intricate reasoning. NVIDIA's Megatron LM stands out as a superior tool in this domain, specifically crafted to adeptly train massive models with billions of parameters.&lt;br&gt;
This write-up will attempt to explore NVIDIA Megatron LM, its architecture configuration, its uses in various applications, and a code walkthrough for training your own Megratron LM. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvsh76cik639zf7u7wlnq.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvsh76cik639zf7u7wlnq.jpg" alt="Image description" width="474" height="195"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h1&gt;
  
  
  A Friendly Intro to NVIDIA Megatron LM?
&lt;/h1&gt;

&lt;p&gt;NVIDIA Megatron LM is a framework designed for training large transformer models that are optimized for distributed GPU architectures. It is built to scale across hundreds or thousands of GPUs, allowing efficient handling of models with billions of parameters. This makes it ideal for advanced natural language processing (NLP) tasks.&lt;/p&gt;

&lt;p&gt;One of Megatron's core advantages is its ability to split training across GPUs and nodes, enabling faster training times and the ability to train very large models that would otherwise be computationally infeasible.&lt;/p&gt;
&lt;h1&gt;
  
  
  Key Features of Megatron LM
&lt;/h1&gt;
&lt;h3&gt;
  
  
  1. Scalable Training
&lt;/h3&gt;

&lt;p&gt;Megatron supports data, model, and pipeline parallelism, which allows for efficient training of large models.&lt;/p&gt;
&lt;h3&gt;
  
  
  2. Mixed-Precision Training
&lt;/h3&gt;

&lt;p&gt;Megatron uses NVIDIA’s AMP (Automatic Mixed Precision) to enhance training performance by reducing memory usage and accelerating computations.&lt;/p&gt;
&lt;h3&gt;
  
  
  3. Optimized for GPUs
&lt;/h3&gt;

&lt;p&gt;Leveraging NVIDIA’s latest GPUs (such as A100 or V100), Megatron is tuned for maximum performance.&lt;/p&gt;
&lt;h3&gt;
  
  
  4. Transformer-based Architecture
&lt;/h3&gt;

&lt;p&gt;Like many modern language models (e.g., GPT-3), Megatron is built on the transformer architecture, which has revolutionized the Natural Language domain.&lt;/p&gt;
&lt;h1&gt;
  
  
  Getting Started with NVIDIA Megatron LM
&lt;/h1&gt;

&lt;p&gt;Now that you have a high-level understanding of Megatron LM, let's explore how to use it in practice.&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;em&gt;Step 1: Setting Up the Environment&lt;/em&gt;
&lt;/h3&gt;

&lt;p&gt;In order to train Megatron models, you will need access to a system with multiple GPUs. The recommended setup is a machine with an NVIDIA GPU and a minimum of 16GB of memory. You can use cloud providers such as AWS, Azure, or Google Cloud to set up instances with NVIDIA GPUs.&lt;/p&gt;

&lt;p&gt;First, let's install the necessary libraries, which include &lt;code&gt;PyTorch&lt;/code&gt; and NVIDIA's &lt;code&gt;Apex&lt;/code&gt; library for mixed-precision training.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Install necessary dependencies
sudo apt update
sudo apt install python3-pip

# Install PyTorch with GPU support
pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113

# Clone Megatron LM repository
git clone https://github.com/NVIDIA/Megatron-LM.git
cd Megatron-LM

# Install Megatron LM dependencies
pip3 install -r requirements.txt

# Install NVIDIA Apex for mixed-precision training
git clone https://github.com/NVIDIA/apex
cd apex
pip3 install -v --disable-pip-version-check --no-cache-dir ./
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  &lt;em&gt;Step 2: Preprocessing the Data&lt;/em&gt;
&lt;/h3&gt;

&lt;p&gt;Megatron requires tokenized input data in a specific format, and datasets can be preprocessed using the provided tokenization scripts. In this example, we'll use an easy-to-go dataset that is, English Wikipedia.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Download English Wikipedia data
wget https://dumps.wikimedia.org/enwiki/latest/enwiki-latest-pages-articles.xml.bz2
bzip2 -d enwiki-latest-pages-articles.xml.bz2

# Run preprocessing
python tools/preprocess_data.py \
  --input enwiki-latest-pages-articles.xml \
  --output-prefix my-wikipedia-data \
  --vocab-file gpt2-vocab.json \
  --merge-file gpt2-merges.txt \
  --dataset-impl mmap \
  --tokenizer-type GPT2BPETokenizer \
  --workers 4

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;This command tokenizes the dataset and converts it into a suitable template for training with the Megatron LM model.&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;em&gt;Step 3: Configuring the Model&lt;/em&gt;
&lt;/h3&gt;

&lt;p&gt;Megatron LM provides a highly customizable setup. For example, you can adjust the number of transformer layers, model size, hidden size, and other parameters. Let's set up a simple transformer model with a small number of layers for demonstration purposes. In traditional machine learning workflows, we usually use a configuration pipeline, so our goal is to adhere to best practices.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Configuration of an LLM model
python pretrain_gpt.py \
    --num-layers 12 \
    --hidden-size 768 \
    --num-attention-heads 12 \
    --micro-batch-size 4 \
    --global-batch-size 16 \
    --seq-length 1024 \
    --max-position-embeddings 1024 \
    --train-iters 10000 \
    --lr 0.0001 \
    --min-lr 1e-5 \
    --lr-decay-style cosine \
    --lr-decay-iters 320000 \
    --lr-warmup-fraction 0.01 \
    --adam-beta1 0.9 \
    --adam-beta2 0.95 \
    --adam-eps 1e-08 \
    --weight-decay 1e-2 \
    --clip-grad 1.0 \
    --tokenizer-type GPT2BPETokenizer \
    --vocab-file gpt2-vocab.json \
    --merge-file gpt2-merges.txt \
    --data-path ./my-wikipedia-data \
    --save ./checkpoints \
    --save-interval 1000 \
    --log-interval 100 \
    --fp16 \
    --tensor-model-parallel-size 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In this configuration:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;num-layers&lt;/em&gt; defines the number of transformer layers.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;hidden-size&lt;/em&gt; sets the size of the hidden layers in each transformer block.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;global-batch-size&lt;/em&gt; specifies the overall batch size across all GPUs.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;lr&lt;/em&gt; and &lt;em&gt;lr-decay-style&lt;/em&gt; define the learning rate and its decay over time.&lt;/li&gt;
&lt;li&gt;The model will checkpoint every 1,000 iterations, allowing you to resume training from the last checkpoint.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  &lt;em&gt;Step 4: Launching the Training Process&lt;/em&gt;
&lt;/h3&gt;

&lt;p&gt;Once the model is set up, you can start training by executing the pretraining script, which is capable of handling both single-node and multi-node GPU setups.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python pretrain_gpt.py \
    --tensor-model-parallel-size 4 \
    --num-layers 24 \
    --hidden-size 1024 \
    --num-attention-heads 16 \
    --micro-batch-size 4 \
    --global-batch-size 32 \
    --seq-length 1024 \
    --train-iters 20000 \
    --lr 0.0001 \
    --data-path ./my-wikipedia-data \
    --save ./checkpoints \
    --fp16

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;This setup will automatically distribute the training across 4 GPUs using model parallelism. The training process may take days or weeks, depending on the model size and GPU power. To get better computation, one might enhance GPU size or use parallel processing using RAPIDS(Refer to my blog):&lt;/p&gt;
&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
      &lt;div class="c-embed__cover"&gt;
        &lt;a href="https://medium.com/@hassan.khsherwani/nvidia-integration-with-databricks-parallel-processing-for-efficient-ml-solutions-013dc1aab0a5" class="c-link s:max-w-50 align-middle" rel="noopener noreferrer"&gt;
          &lt;img alt="" src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A144%3A144%2F1%2AfjzEmcFKtZQ2GJtverLyJA.jpeg" height="144" class="m-0" width="144"&gt;
        &lt;/a&gt;
      &lt;/div&gt;
    &lt;div class="c-embed__body"&gt;
      &lt;h2 class="fs-xl lh-tight"&gt;
        &lt;a href="https://medium.com/@hassan.khsherwani/nvidia-integration-with-databricks-parallel-processing-for-efficient-ml-solutions-013dc1aab0a5" rel="noopener noreferrer" class="c-link"&gt;
          Nvidia Integration with Databricks: Parallel processing for efficient ML solutions | by Hassan Sherwani | Oct, 2024 | Medium
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;p class="truncate-at-3"&gt;
          In the ever-evolving landscape of artificial intelligence(AI) and data science, speed and scalability are key. As models grow larger and…
        &lt;/p&gt;
      &lt;div class="color-secondary fs-s flex items-center"&gt;
          &lt;img alt="favicon" class="c-embed__favicon m-0 mr-2 radius-0" src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fv2%2F5d8de952517e8160e40ef9841c781cdc14a5db313057fa3c3de41c6f5b494b19" width="32" height="32"&gt;
        medium.com
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;em&gt;Step 5: Fine-Tuning the Model&lt;/em&gt;
&lt;/h3&gt;

&lt;p&gt;After pretraining, you might want to fine-tune the model for specific tasks such as text classification or question answering. Fine-tuning involves loading the pre-trained weights and further training on a smaller, task-specific dataset.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python tools/finetune_gpt.py \
    --pretrained-checkpoint ./checkpoints \
    --task TASK_NAME \
    --data-path ./task-specific-data \
    --num-layers 24 \
    --hidden-size 1024 \
    --num-attention-heads 16 \
    --seq-length 1024 \
    --train-iters 5000 \
    --lr 0.00001 \
    --global-batch-size 16 \
    --fp16

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace TASK_NAME with the name of the task (e.g., text generation, classification, Q&amp;amp;A chatbot etc), and the data path should point to the relevant dataset.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;NVIDIA Megatron LM is a powerful tool for training massive language models, offering unparalleled scalability and performance. By following the steps outlined in this blog, you can start building and training your own large language models, fine-tuning them for specific NLP tasks, and leveraging the cutting-edge advancements in the AI field.&lt;/p&gt;

&lt;p&gt;With frameworks like Megatron LM, we are entering an era where language models can be used for truly transformative applications. These applications include real-time translation and generating human-like responses in conversation. Whether you are a researcher or a developer, experimenting with Megatron can lead to new possibilities in AI-driven innovation.&lt;/p&gt;

&lt;p&gt;Stay tuned for more!&lt;/p&gt;

&lt;h1&gt;
  
  
  References
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;Nvidia Debuts Enterprise-Focused 530B Megatron Large Language Model and Framework at Fall GTC21: &lt;a href="https://www.aiwire.net/2021/11/09/nvidia-debuts-enterprise-focused-530b-megatron-large-language-model-and-framework-at-fall-gtc21/" rel="noopener noreferrer"&gt;https://www.aiwire.net/2021/11/09/nvidia-debuts-enterprise-focused-530b-megatron-large-language-model-and-framework-at-fall-gtc21/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Nvidia Megatron core: &lt;a href="https://docs.nvidia.com/megatron-core/index.html" rel="noopener noreferrer"&gt;https://docs.nvidia.com/megatron-core/index.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism: &lt;a href="https://arxiv.org/abs/1909.08053" rel="noopener noreferrer"&gt;https://arxiv.org/abs/1909.08053&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Hugging Face documentation: &lt;a href="https://huggingface.co/docs/accelerate/en/usage_guides/megatron_lm" rel="noopener noreferrer"&gt;https://huggingface.co/docs/accelerate/en/usage_guides/megatron_lm&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Apex Documentation: &lt;a href="https://github.com/NVIDIA/apex" rel="noopener noreferrer"&gt;https://github.com/NVIDIA/apex&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>nvidia</category>
      <category>megratronlm</category>
      <category>llm</category>
      <category>genai</category>
    </item>
  </channel>
</rss>
