<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Austin Choi on Medium]]></title>
        <description><![CDATA[Stories by Austin Choi on Medium]]></description>
        <link>https://medium.com/@austinchoi?source=rss-449ce1377e40------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Austin Choi on Medium</title>
            <link>https://medium.com/@austinchoi?source=rss-449ce1377e40------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:02:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@austinchoi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Enable Multi-Agents + Classic ML using Databricks and DSPy!]]></title>
            <link>https://medium.com/@austinchoi/enable-multi-agents-classic-ml-using-databricks-and-dspy-918f78c16e3a?source=rss-449ce1377e40------2</link>
            <guid isPermaLink="false">https://medium.com/p/918f78c16e3a</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[dspy]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Austin Choi]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 00:21:35 GMT</pubDate>
            <atom:updated>2025-01-29T19:16:54.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMpe2VxFMxkCoLrJicrA7g.png" /></figure><p>Today, I’ll walk you through a multi-agent chatbot solution powered by both LLMs and traditional machine learning models. By the end of this article, you’ll learn:</p><ol><li>When you should use Agents</li><li>When you should use Traditional Machine Learning</li><li>Why I chose DSPy and Databricks</li></ol><p>Ultimately, <strong>you don’t need agents for everything</strong>. Not every chatbot needs an agent, and not every GenAI solution requires one!</p><h4><strong>Introduction</strong></h4><p>As a reminder, while this solution is demonstrated through a chatbot to showcase how Agents work together and answer questions, chatbots are not the only use case! Though it may appear simple on the surface, there is significant complexity happening behind the scenes. Chatbots provide an excellent visual demonstration of the underlying processes. If this were refactored into an ETL pipeline use case, these interactions would not be visible!</p><p>This solution uses DSPy to build individual agents and their associated tools. We leverage the logic and outputs from dspy.Signature to enable communication between agents and help them “talk” to each other.</p><p>These are the agents built for this solution:</p><ol><li><strong>Router Agent</strong>: This agent reviews questions and determines which specialized agent can best provide answers</li><li><strong>Vision Agent:</strong> This agent only determines which Computer Vision model to use depending on the task the user is asking for. In this solution, the agent uses a Vision Transformer model (BeIT) for image classification and Tesseract for OCR. These models are hosted on Databricks Model Serving.</li><li><strong>Databricks Agent:</strong> This agent utilizes Databricks’ Vector Search to perform traditional RAG on a Databricks Documentation knowledge base. When necessary, it breaks down complex questions into subquestions to gather more information.</li><li><strong>Pokemon Agent:</strong> This agent uses PokeAPI to retrieve the latest information about a particular Pokemon. It identifies the Pokemon in the user’s question and retrieves data through external API calls.</li><li><strong>Sales Agent:</strong> This agent simply simulates a sales conversation with tools to execute order and look up item numbers.</li></ol><p>Roughly, this is how the Agents are connected with each other:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1B7E0f5DWUiLySiq" /></figure><p>Productionalizing a solution like this is not easy. This code and any future solutions will be a small portion of the overall production solution. Most importantly, since the data used to inform these Agents directly influences their performance, it is critical to have a platform that simplifies data access and engineering.</p><p>Thus, I built this solution on Databricks because of its flexibility, extensive tool ecosystem, and my familiarity with the platform (I work there after all!). Rather than being locked into a specific framework, I can choose the one that best suits my needs! This versatility enabled me to build a production-ready, end-to-end solution on a unified platform. Here are the tools that made this possible:</p><ol><li><strong>Unity Catalog:</strong> Used for data storage and asset governance which includes the tools and models I used for this solution</li><li><strong>Databricks Notebooks:</strong> Used for direct access to my data, models, tools and so forth as I did development with DSPy</li><li><strong>MLflow:</strong> Used to register models, track metrics, do tracing and do versioning on Unity Catalog. I have a few iterations of this solution as various versions on Unity Catalog thanks to MLflow.</li><li><strong>Mosaic AI Agent Framework:</strong> Used to evaluate my agents, individually, to ensure they were production ready.</li><li><strong>Mosaic Model Serving:</strong> Used to host my solution and take advantage of AI Gateway to handle traffic, guardrails and other operational tools</li><li><strong>Databricks Apps:</strong> Used to quickly deploy my solution on a Gradio UI!</li></ol><p>Roughly, here is what a sample solution architecture looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ifWitWHRts45rDC3" /></figure><p>Finally, why did I pick DSPy? There are so many frameworks out there designed to build out agents like Langgraph, LlamaIndex, SmolAgents, CrewAI, and so on, each with their own advantages. However, over time, I grew incredibly tired of writing and re-writing prompts that just grew longer and more complex. t’s very difficult to maintain static walls of text, and these frameworks still depend on you writing a good prompt to work effectively, requiring significant manual effort. When you also begin to modularize your agents, those are additional, independent prompts you have to manage. The amount of prompts you’re managing is going to become very unwieldy very quickly.</p><p>This is where DSPy steps in. DSPy enables you to programmatically create prompts for your GenAI application. DSPy is designed with inspiration from PyTorch’s modular neural network implementation. You can define specific modules for specific tasks and combine them under one module for a holistic solution. DSPy provides ways to ‘optimize’ your prompts based on a dataset, similar to training a machine learning model. Users typically see an uplift of 10% — 30% just from doing this, depending on what module they are optimizing. This approach is far more sustainable in the long run than building up and maintaining a prompt library.</p><p>One disadvantage of DSPy has been its agent framework integration. Langgraph has made it incredibly easy to connect agents and enable communication between them. Its UI is very intuitive, and anyone can get started quickly with Langgraph. However, you still need to write extensive prompts to get the agents working effectively.</p><p>You can see a great analysis on LLM Framework abstractions by Two Sigma here: <a href="https://www.twosigma.com/articles/a-guide-to-large-language-model-abstractions/">https://www.twosigma.com/articles/a-guide-to-large-language-model-abstractions/</a></p><p>Here’s a video Demo of the solution!</p><p><a href="https://vimeo.com/manage/videos/1048033201/8e88c94bcd">https://vimeo.com/manage/videos/1048033201/8e88c94bcd</a></p><p>Here’s a link to the code if you’d like to build this yourself!</p><h3><strong>Section 1: When to use Agents?</strong></h3><p>Now, it’s clear in the demo that the Agents are working and they’re responding pretty well. Frankly, this is a minimum requirement for any kind of chatbot-like use case. If my chatbot is not accurate or provides incorrect information, I risk serious consequences such as when Air Canada was liable to a partial refund when their chatbot hallucinated.</p><p>But, we need to understand why we are even using Agents here. How is this better than just asking ChatGPT the same question? Let’s walk through some of the Agents and see how they compare against foundation models without any additional prompting.</p><p>As a sidenote, while I state what LLM I used to power the Agent, you can easily switch them out to whatever LLM you prefer as long as the model supports function calling! So a base Phi-4 model won’t work here unless it was fine-tuned to learn function calling.</p><p>Below I cover three agents: Pokemon, Vision and Databricks.</p><p>Fundamentally, what makes this Agentic is that the Agents first reason whether they can answer a question. But, at any moment in the conversation if another Agent that can better answer the question, they pass it on. How they answer the question varies by agent.</p><h4>Pokemon Agent</h4><p>Model used: Llama-8B</p><p>Let’s start with the Pokémon agent. I made this agent to demonstrate the need to use existing databases and services for the most up-to-date information. It’s an example of an agent deciding when to use a tool, identifying the necessary parameters, and returning a confident answer.</p><p>New Pokémon are always being released and updated. There are over 1,000 Pokémon now, though each year typically adds only a handful of new Pokémon to the Pokédex. However, this means that foundation models with knowledge cutoffs do not know about the newest Pokémon. It’s also not feasible to constantly fine-tune or retrain the model just to include knowledge of a few more Pokémon.</p><p>To demonstrate this, here is ChatGPT and Claude, side by side, trying to answer a question about Sinistcha, a Pokemon introduced in Generation 9 as apart of the Teal Mask DLC. It is a Grass/Ghost dual type.</p><p>Claude</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*NCCKelzbNbHkqclH" /></figure><p>ChatGPT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*qu0sKFndGgJGAWyt" /></figure><p>Note Claude’s lack of confidence and ChatGPT has approximations but there are mistakes in the base stats like HP, which should be 71. These are exact numbers and shouldn’t be approximated.</p><p>Since I don’t know every single Pokémon, and it wouldn’t be worth the effort to build my own database of all 1,000+ Pokémon with their details (stats, moves, abilities, biology, nature, and so much more), I would like an agent to identify potential Pokémon in questions and use existing resources like PokéAPI to ensure we have accurate information.</p><p>The result is a confident and accurate answer of the Pokemon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*uy1bVXPVltwZo4ev" /></figure><p>This Agent’s task was very straightforward, and I could use Llama 8B since it only needed to call the function and find the Pokémon name. This choice improved latency by nearly 80% compared to using Claude, GPT-4, and Llama-405B.</p><p><strong>Key Takeaways:</strong></p><ol><li>Agents can access the latest information depending on the function you provide</li><li>Agents know to use tools to get accurate information</li><li>The task was simple enough to use a much smaller model which improved performance</li></ol><h4>Vision Agent</h4><p>Model used: Llama-8B</p><p>This agent demonstrates how Traditional Machine Learning (ML) can enhance Generative AI applications without relying solely on large language models. Using GPT-4 or Claude for every task is unnecessarily expensive — it’s like using a sledgehammer to crack a walnut. Traditional ML is more cost-effective, faster, and provides more consistent results. Combining both approaches delivers the best of both worlds.</p><p>So, instead of using existing multi-modal capabilities from Generative AI models, I had Llama-8B decide which computer vision model to use based on the user’s question.</p><p>I loaded two distinct computer vision models to Databricks’ Model Serving to demonstrate this reasoning: BeIT and Tesseract. These models are “normal” sized models, provide a response instantly, and cost pennies compared to LLMs to host.</p><p>Below is a comparison of asking Claude and ChatGPT to do the same task. I am comparing pay per token for Claude and GPT-4o because:</p><ol><li>We can’t host Claude and GPT-4o</li><li>Hosting an LLM (for production) is incredibly expensive compared to hosting a traditional ML Model, even Llama-70B is magnitudes more expensive than using traditional ML</li></ol><p>We are also going to use a very, very small amount of requests per hour just to make it remotely competitive. In a production setting, I know 20 requests per hour is incredibly small, almost unrealistic. But it exemplifies how expensive it is right now to run inference on these models.</p><p><strong>Task: OCR</strong></p><p>Model: Claude-Sonnet</p><p>Time: &lt;1 second</p><p>Price assuming 20 requests per hour PPT for LLMs: $0.07 per request of $1.40 per hour</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AL_Wbl50pTnr-uTBuCcJBA.png" /></figure><p>Model: ChatGPT</p><p>Time: &lt;1 second</p><p>Price assuming 20 requests per hour PPT for LLMs: $0.05 per request of $1.00 per hour</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*bpmFTTi3yKLr7hhLjAqdZg.png" /></figure><p>Model: Tesseract</p><p>Time: &lt;1 second</p><p>Price: $0.7 per hour (hundreds of thousands of requests)</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6590VbFeX5d6D3hRuvyzA.png" /></figure><p><strong>Task: Image Classification</strong></p><p>Model: Claude-Sonnet</p><p>Time: &lt;1 second</p><p>Price assuming 20 requests per hour PPT for LLMs: $0.05 per request of $1.00 per hour</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*P2Ef8v-SiaZg9MakB2oJYw.png" /></figure><p>Model: ChatGPT</p><p>Time: &lt;1 second</p><p>Price assuming 20 requests per hour PPT for LLMs: $0.04 per request of $0.08 per hour</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*DaUcdp0xu7ghkno2EWg99g.png" /></figure><p>Model: Vision Transformer BeIT</p><p>Time: &lt;1 second</p><p>Price: $0.7 per hour (hundreds of thousands of requests)</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JIC3uPNz6LmHKDh8IUf2VQ.png" /></figure><p>Key Takeaway:</p><ol><li>It’s likely a machine learning model can get your use case done more effectively in performance AND cost</li><li>Combining a machine learning model and a smaller LLM model combines the best of both models together.</li><li>Traditional Machine Learning is so much cheaper that you should probably use that</li></ol><h4>Databricks Agent</h4><p>This agent demonstrates a classic implementation of Retrieval-Augmented Generation (RAG) with an additional capability: breaking complex questions into simpler subquestions when necessary. This feature is important because users often ask questions that are either too broad or contain too many keywords, making it difficult to retrieve relevant information. Additionally, we often limit the amount of information retrieved per query to manage costs. It’s helps to formulate additional questions for additional information retrieval.</p><p>One example of this is “What is the benefit of Delta Tables and Apache Spark”. There are two distinct topics here: Delta Tables and Apache Spark. If our retriever database is limited to just pulling 3 chunks of information, we have to hope that our information will contain either both topics in each chunk or one chunk per topic, which may not have enough information if chunked improperly.</p><p>The LLM can take this question and split this question into the following two questions:</p><ol><li>What are Delta Tables?</li><li>What is Apache Spark?</li></ol><p>Then the vector search can specifically pull information specific to Delta Tables first, then specific to Apache Spark second. The LLM will review both information, consolidate them and answer the question.</p><p>Key Takeaway:</p><ol><li>Use an Agent to improve your inputs so that your downstream tools function better</li></ol><p>Now that we have an idea of how these Agents are behaving, let’s try to get them to work together!</p><h3><strong>Section 2: DSPy: How are the agents connected?</strong></h3><p>Every implementation of agents needs some way to read memory or the context of the past inputs and outputs to be caught up on everything that’s happened so far. Think of this as a “state” that’s passed around so that each agent knows exactly what is happening.</p><p>DSPy does not have a built-in way to connect Agents together like Langgraph Edges. But we can take advantage of how DSPy signatures enforce typing and outputs to direct the application to the next Agent.</p><p>If you don’t know how DSPy works, please check out that article for a quick overview! <a href="https://www.dbreunig.com/2024/12/12/pipelines-prompt-optimization-with-dspy.html">https://www.dbreunig.com/2024/12/12/pipelines-prompt-optimization-with-dspy.html</a></p><p>I won’t go as deeply into how each component of DSPy works here as DSPy has great tutorials demonstrating this: <a href="https://dspy.ai/learn/">https://dspy.ai/learn/</a></p><p>I will walk through how I walked through developing an agent using DSPy’s signatures. This will not cover evaluation and optimizations since the article is already pretty long.</p><h4>DSPy Signatures</h4><p>DSPy signatures represent the instructions that will generate the prompt used with the LLM. Think of this as a recipe: It has a set of ingredients (inputs) that should create a dish (output)!</p><p>Like a recipe, you can specify initial instructions and parameters. And just as a recipe is designed for a specific dish — you wouldn’t use a cheesecake recipe to make tiramisu — each signature needs to be tailored to its specific task. A good signature, like a good recipe, should be clear and accomplish its intended purpose effectively.</p><p>Each Agent requires its own signature that clearly defines and addresses a specific task.</p><p>Let’s take a look at the vision Agent signature.</p><p>First, we need to declare a dspy.Signature class:</p><pre>class vision_agent(dspy.Signature):</pre><p>This class will eventually be passed into a dspy.Module but we will get to that later.</p><p>Then, we need to define an initial set of instructions in the docstring. This is entirely optional since DSPy uses everything within a class to make the prompt so the variable name, class name and typing all influence how the prompt is created.</p><pre>class vision_agent(dspy.Signature):<br>  &quot;&quot;&quot;<br>  &quot;You are an expert vision model selection agent<br>  &quot;Review the conversation_history for relevant context. If it&#39;s a transfer to you, greet the user and resume the conversation.&quot;<br>  &quot;If at any point the question is not about vision models, do not answer the question and say you are transferring the user to the right agent and transfer them to the next_agent&quot;<br>  &quot;Follow the following routine with the user:&quot;<br>  &quot;1. Identify the task based on the user&#39;s question. It must be ocr or classification.&quot;<br>  &quot;2. Identify the url in the user&#39;s question&quot;<br>  &quot;3. Send the url and task to the vision_transformer tool as url and task&quot;<br>  &quot;4. Respond the the tool output&quot;<br>  &quot;5. Add your response to the history in this format {&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: your answer here}&quot;<br>  &quot;6. Continue assisting the user until otherwise.&quot;<br>  &quot;7. If the user is satisfied or the user asks a question not related to vision models, select the proper next_agent. Use the router_agent if you&#39;re not sure. Use image_expert if not required&quot;<br>  &quot;&quot;&quot;</pre><p>The next step is to define at least one dspy.InputField() and one dspy.OutputField(). These fields tell DSPy which variables serve as inputs and outputs, allowing it to enforce the appropriate type checking. You can specify various data types to ensure your outputs conform to the expected format.</p><p>Here are the inputs and outputs for the vision_agent signature:</p><pre>user_question: str = dspy.InputField()<br>conversation_history: Optional[list] = dspy.InputField()<br>response: str = dspy.OutputField()<br>history: dict = dspy.OutputField()<br>next_agent: Literal[&#39;pokemon_expert&#39;,&#39;databricks_expert&#39;,&#39;image_expert&#39;, &#39;sales_expert&#39;, &#39;router_agent&#39;] = dspy.OutputField()<br>So to put the signature altogether:<br>class vision_agent(dspy.Signature):</pre><p>So to put the signature altogether:</p><pre>class vision_agent(dspy.Signature):<br>  &quot;&quot;&quot;<br>  &quot;You are an expert vision model selection agent<br>  &quot;Review the conversation_history for relevant context. If it&#39;s a transfer to you, greet the user and resume the conversation.&quot;<br>  &quot;If at any point the question is not about vision models, do not answer the question and say you are transferring the user to the right agent and transfer them to the next_agent&quot;<br>  &quot;Follow the following routine with the user:&quot;<br>  &quot;1. Identify the task based on the user&#39;s question. It must be ocr or classification.&quot;<br>  &quot;2. Identify the url in the user&#39;s question&quot;<br>  &quot;3. Send the url and task to the vision_transformer tool as url and task&quot;<br>  &quot;4. Respond the the tool output&quot;<br>  &quot;5. Add your response to the history in this format {&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: your answer here}&quot;<br>  &quot;6. Continue assisting the user until otherwise.&quot;<br>  &quot;7. If the user is satisfied or the user asks a question not related to vision models, select the proper next_agent. Use the router_agent if you&#39;re not sure. Use image_expert if not required&quot;<br>  &quot;&quot;&quot;<br>  user_question: str = dspy.InputField()<br>  conversation_history: Optional[list] = dspy.InputField()<br>  response: str = dspy.OutputField()<br>  history: dict = dspy.OutputField()<br>  next_agent: Literal[&#39;pokemon_expert&#39;,&#39;databricks_expert&#39;,&#39;image_expert&#39;, &#39;sales_expert&#39;, &#39;router_agent&#39;] = dspy.OutputField()</pre><p>This signature expects a user_question as a string and the conversation history as a list. It will follow the instructions in the docstring and create the following:</p><ol><li>A string response to show the user</li><li>A dictionary history storing what the user_question and response was to store later into memory</li><li>A string of one of the options in the Literal so that we always know which agent to go to next. The Literal tells DSPy to only output the provided value.</li></ol><p>You’ll notice in the docstring that I call out specific tools and when to use them. This is important to accurately use function calling in the dspy.Module.</p><p>But, now that we have our signature, we can begin building our module!</p><h4>Modules</h4><p>DSPy Modules execute instructions defined in their signatures. Each module creates prompts and sends them to the LLM for processing. You can think of a module as a chef following the recipe we created earlier!</p><p>While DSPy provides built-in modules like dspy.Predict and dspy.ChainOfThought, developers can also use dspy.Module to create custom modules containing multiple interacting submodules. This modular architecture forms the foundation for how agents communicate and work together in DSPy.</p><p>The most important modules we use for this solution are dspy.Predict and dspy.ReAct. Dspy.Predict will take the signature, create the prompt, and execute the prompt against a LLM. All you need to provide is a signature.</p><p>Dspy.ReAct is a combination of built-in modules to enable function calling. Dspy.ReAct expects a signature and a list of tools it has access to. One example of this is in my Vision Agent, where I defined python functions to be used as tools such as the vision_lookup tool to ping Databricks Model Serving.</p><p>Here’s how you would set up the Vision Agent to test.</p><p>Pass the signature and tools into the module ReAct</p><pre>vision_agent_class = dspy.ReAct(vision_agent, tools=[self.vision_tool], max_iters=1)</pre><p>Then, ask your question! Remember, the vision_agent signature expects a user_question as a string and conversation_history as a list. DSPy enforces this for us at the Module level! If you do not provide these two inputs, it WILL throw an error.</p><pre>result = vision_agent_class(user_question=&quot;What is this image?&quot;, conversation_history=[])</pre><p>What you end up with is a result containing all the outputs you specified. And you will always get something for those outputs. You can access each individual output by the name you specified in the signature. There’s an example below:</p><pre>result.response #this would return the model&#39;s response in a string<br>result.history #this would be the response in a dict format: {&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: model&#39;s response}<br>result.next_agent #this would be the &#39;image_expert&#39; since there is no indication we need to move agents</pre><p>Being able to both enforce typing and programmatically pull the specific outputs I was requesting allowed me to tie everything together dynamically, knowing for sure that I would get a certain kind of output. I did not have to parse through and find the right output in the output from the LLM.</p><h4>Creating Submodules in a Module</h4><p>Now that we understand how modules work, we can replicate this for all our agents. Each agent’s signature is passed into a dspy.ReAct module since they all have at least one tool to call.</p><p>To put this altogether, we create our own dspy.Module and initiate each of them in the init function like below:</p><pre>class multi_agent_module(dspy.Module):<br>  def __init__(self):<br>  mlflow.dspy.autolog()<br>  self.router_agent_class = dspy.Predict(router_agent)<br>  self.pokemon_agent_class = dspy.ReAct(pokemon_agent, tools=[self.pokemon_lookup], max_iters=1)<br>  self.databricks_agent_class = dspy.ReAct(databricks_agent, tools=[self.databricks_documentation], max_iters=1)<br>  self.vision_agent_class = dspy.ReAct(vision_agent, tools=[self.vision_tool], max_iters=1)<br>  self.sales_agent_class = dspy.ReAct(sales_agent, tools=[self.execute_order], max_iters=1)</pre><p>When creating a custom dspy.Module, you must define a forward function, similar to PyTorch’s requirement. For experienced PyTorch developers, this concept will be familiar. For others, the forward function serves as the pathway through which input data flows through the neural network’s layers to generate predictions or outputs.</p><p>In that sense, DSPy’s submodules are like the neural network layers and forward() takes in the input data to handle which layer to go to next.</p><p>Here’s how the forward function looks here:</p><pre>def forward(self, question, messages, next_agent):<br>  &quot;&quot;&quot;Main interaction loop&quot;&quot;&quot;<br>  next_agent, messages, response_text = self.handle_question(question=question, messages=messages, next_agent=next_agent)<br>  return next_agent, messages, response_text</pre><p>There is a significant amount of code in between the __init__ and forward() functions like the tools the Agents have access to and other necessary processing python functions.</p><p>Remember the next_agent parameter we included in the signature? We can now use that output in this module&#39;s handle_question function. Since DSPy is highly reliable and guarantees we&#39;ll receive one of the predefined Literal values, we can easily transition to the next agent when needed. All we need to do is replace the next_agent variable with result.next_agent, and handle_question in the code above will automatically switch to the specified agent! I&#39;ve built a Gradio demo that visualizes this transfer process and displays the current active agent, making it clear to viewers when these transitions occur.</p><p>Now, all you need to do to call this completed module (multi_agent_module is what it is called in the code) is call it like you would any other dspy.Module!</p><pre>multi_agent = multi_agent_module() #multi_agent_module is the module we created will the submodules<br>result = multi_agent()# You can ask for input data in the forward function and it will expect to see those inputs. This module we built does not expect an initial input</pre><h3><strong>Section 3: Why on Databricks?</strong></h3><p>Databricks offers numerous features that streamline the development lifecycle and make application productionization straightforward. While I’ve mentioned tools like Unity Catalog and MLflow, the requirements for productionizing Agents match those of traditional ML systems.</p><p>These requirements include MLOps/LLMOps capabilities, version control systems, monitoring and evaluation tools, and A/B testing frameworks, among others. Databricks illustrates these production requirements well in their diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Pt0pP_6hx24toN1" /><figcaption>This image was adapted for a demonstration!</figcaption></figure><h4>AI Gateway</h4><p>Using AI Gateway gives me peace of mind that my LLM endpoint will NOT be abused. It is an out of the box layer that Databricks provides in its model serving capabilities. I can set specific guardrails, throttle traffic and select multiple LLMs to use incase one fails. Additionally, it sets up inference tables for me so that I can review the requests sent to my LLM for future evaluations</p><p>Here is an example of AI Gateway in action:</p><p>First, without AI Gateway, nothing happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zx5oJGzIPI6nSXj1iCwyTQ.png" /></figure><p>But once I add a few guardrails as shown here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTSjeKtanYYox7rbHPDBwA.png" /></figure><p>I can completely block the LLM from responding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lo7boMTSwiQxTvPy2veLnw.png" /></figure><p>Here is an example of a step by step workflow that I took to set up the Databricks Agent for success:</p><ol><li>Used a Databricks Notebook to do ETL on PDFs collected stored in a Volume in Unity Catalog</li><li>Chunked and created Embeddings for the PDFs using GTE on Databricks Foundation Model API service</li><li>Created a Vector Index and Vector Search Endpoint to create a Vector Database for the Databricks Agent to use</li><li>Steps 1–3 will repeat when new PDFs arrive or still need to be processed</li></ol><p>Once I had my agents, I followed this process to get them tested and production ready:</p><ol><li>Designed the entire multi-agent solution through Notebooks and DB connect (for local testing)</li><li>Databricks Mosaic AI Agent Framework Synthetic Data Generation to create some synthetic data that I did not have</li><li>Used DSPy Optimizer to optimize my Agent’s prompts</li><li>Used Databricks Mosaic AI Agent Framework to evaluate my agent’s performance after DSPy optimization.</li><li>Used MLflow to register and log the model to Unity Catalog.</li><li>In this case, an MLflow has a DSPy flavor and can easily be saved as an MLflow model. It is not a model in the traditional machine learning sense.</li><li>Used Databricks Model Serving to host the MLflow model</li><li>Use AI Gateway to monitor the LLM, set up guardrails and throttle traffic</li><li>Used Databricks App to serve a Gradio UI interface!</li></ol><h4><strong>In Summary</strong></h4><p>There is A LOT going on for what looks like a very simple chatbot. And that’s expected. If this was easy, everyone would be doing it after all. At scale, I only anticipate this to become harder but there is so much more that goes into Agents from the code you build for it.</p><p>That is why I used DSPy and Databricks to remove a lot of the recent headaches that come with prompt engineering and productionalizing GenAI. Everything I needed is right there and became a fun and powerful project to do!</p><p>I hope you learned something new today! If you’re interested in continuing this conversation, find me on LinkedIn! <a href="https://www.linkedin.com/in/austin-c-18867abb/">https://www.linkedin.com/in/austin-c-18867abb/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=918f78c16e3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finally, My Gaming GPU can Optimally Fine-Tune LLMs]]></title>
            <link>https://medium.com/@austinchoi/finally-my-gaming-gpu-can-optimally-fine-tune-llms-cfd3b88e30ed?source=rss-449ce1377e40------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfd3b88e30ed</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[nvidia]]></category>
            <dc:creator><![CDATA[Austin Choi]]></dc:creator>
            <pubDate>Tue, 28 May 2024 01:30:53 GMT</pubDate>
            <atom:updated>2024-05-28T01:30:53.796Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Cost-Effective and optimal LoRA Fine-Tuning Phi3-mini with a single 3080 RTX GPU with Unsloth</strong></h4><h3>The Inspiration</h3><p>A close friend (<a href="https://www.linkedin.com/in/vishnu-talla-pmp/">Vishnu Talla</a>) and data scientist sent over a new fine-tuning framework that he discovered: Unsloth from Unsloth AI. I was excited to see another fine-tuning framework but this was different. Not only did the Unsloth AI founders manage to create they created a simple and elegant fine-tuning and inference framework for smaller and/or quantized models, (with improvements over Flash Attention 2 by over 2x!) but they also enabled fine tuning with RTX GPUs! From the 40 series RTX GPUs all the way to decades old 10 series GPUs, anyone (almost all gamers) would theoretically be able to fine-tune these state-of-the-art LLMs. All this while maintaining incredible performance!</p><p>I’m hooked. And had to try it on my own 3080. Fine tuning LLMs is becoming more and more important as we mature in production ready GenAI applications such as RAG. We know there are limitations and a lot of research and tools like <a href="https://contextual.ai/introducing-rag2/">RAG 2.0</a> are coming out to address them. At the same time, we are still optimizing how we fine-tune these LLMs. One area of hot debate is with Parameter Efficient Fine Tuning (PEFT) methods like LoRA adapters. Research is still coming out around best practices with LoRA thanks to Dan Biderman et al, Columbia University and the Databricks Mosaic team in the paper <a href="https://arxiv.org/abs/2405.09673">LoRA Learns Less and Forgets Less</a>. A very interesting read in understanding some differences between full fine-tuning and PEFT.</p><p>All this uncertainty made my head swim and the inaccessibility/cost of GPUs (not RTX but A100/H100) just discouraged me from trying fine-tuning LLMs of any kind. Other fine tuning frameworks like llama-factory or Axoltol were designed with fine-tuning on larger gpus in mind making training on our single consumer RTX GPUs complicated and inefficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*9vFcuSGRMdwRiwK1.jpg" /><figcaption>The GPU I plan on using for training</figcaption></figure><p>That’s where Unsloth comes in and why I’m excited to see the optimizations that enable an unseen level of performance in training and inference at this level. They are a start up of two brothers: Daniel and Michael Han. They recently released this framework in the past several months and are still releasing models today!</p><p>Here are some of their features copied from their <a href="https://github.com/unslothai/unsloth">github repo</a></p><ul><li>All kernels written in <a href="https://openai.com/research/triton">OpenAI’s Triton</a> language. Manual backprop engine.</li><li>0% loss in accuracy — no approximation methods — all exact.</li><li>No change of hardware. Supports NVIDIA GPUs since 2018+. Minimum CUDA Capability 7.0 (V100, T4, Titan V, RTX 20, 30, 40x, A100, H100, L40 etc) <a href="https://developer.nvidia.com/cuda-gpus">Check your GPU!</a> GTX 1070, 1080 works, but is slow.</li><li>Works on Linux and Windows via WSL.</li><li>Supports 4bit and 16bit QLoRA / LoRA finetuning via <a href="https://github.com/TimDettmers/bitsandbytes">bitsandbytes</a>.</li><li>Open source trains 5x faster — see <a href="https://unsloth.ai/">Unsloth Pro</a> for up to 30x faster training!</li></ul><p>The work here is incredibly impressive for the two brothers. It’s allowing people with limited to no access to expensive GPUs to try fine tune and create their own models for the cost of your own electricity. If you don’t have a GPU, they have Colab notebooks set up for you to get started right away! It’s getting easier and easier to train and tinker with LLMs and I look forward to seeing what else people can do with frameworks like Unsloth!</p><p>The rest of this article will highlight my experience using Unsloth, fine-tuning a quantized Phi3-mini-instruct model from Unsloth and the results I found.</p><h3>The Specs</h3><p>Here is the hardware I was working with:</p><p>GPU: Nvidia 3080 with 10GB VRAM <br>CPU: AMD 5600x <br>RAM: 16GB GDDR4 <br>Main Purpose: To play Animal Well, High-Fi Rush, The Finals and Apex Legends</p><h3>The Model</h3><p>Original Model: <a href="https://huggingface.co/microsoft/Phi-3-mini-4k-instruct">https://huggingface.co/microsoft/Phi-3-mini-4k-instruct</a> <br>Unsloth Model: <a href="https://huggingface.co/unsloth/Phi-3-mini-4k-instruct">https://huggingface.co/unsloth/Phi-3-mini-4k-instruct</a><br>Quantized Model: <a href="https://huggingface.co/unsloth/Phi-3-mini-4k-instruct-bnb-4bit">https://huggingface.co/unsloth/Phi-3-mini-4k-instruct-bnb-4bit</a></p><p>I particularly like the performance to size ratio of this new model from Microsoft Azure. Since PEFT only adjusts a small percentage of weights, I wanted to use a model that performed well originally and smaller in parameter size.</p><h3>The Data</h3><p>Original Dataset: <a href="https://huggingface.co/datasets/databricks/databricks-dolly-15k">https://huggingface.co/datasets/databricks/databricks-dolly-15k</a><br>Modified Dataset: <a href="https://huggingface.co/datasets/philschmid/dolly-15k-oai-style">https://huggingface.co/datasets/philschmid/dolly-15k-oai-style</a></p><p>I chose the Dolly dataset as it was one of the first open source genai related models and datasets that I discovered. Databricks did a fantastic job for one of the first open source LLMs and it felt right to go back to what started me on this journey.</p><p>Additionally, the dataset was generated purely by Databricks employees which gives me confidence that this is generally what people want to see in an output and how to best follow instructions. Given that it’s an open source dataset that has been out for over a year, there is a high likelihood Phi3 and many other LLMs have used this dataset to train their own models so we are at risk of overfitting on this dataset. The dataset must be high quality with over 300 tracked huggingface models fine tuned using the dataset (definitely higher!</p><p>My hope is that this data well help Phi3 listen to instructions better and following the examples in a few shot prompt better.</p><p>We use the Modified Dataset to map the data to Phi3’s chat template since someone else already did the data engineering to adjust the Dolly dataset to put it in an OpenAPI (OAI) style. (saves me some data engineering work)</p><h3>The Code</h3><p>I followed Unsloth’s example Colab notebook here: <a href="https://colab.research.google.com/drive/1lN6hPQveB_mHSnTOYifygFcrO8C1bxq4?usp=sharing">https://colab.research.google.com/drive/1lN6hPQveB_mHSnTOYifygFcrO8C1bxq4?usp=sharing</a></p><p>Check out their repo here: <a href="https://github.com/unslothai/unsloth">https://github.com/unslothai/unsloth</a></p><p>You also get this cool sticker on your model when you upload the model to hugginface!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*zQqP5xpOblFc30uL.png" /></figure><h4>Step 1: Download the Model</h4><p>We will use the quantized model from Unsloth for optimal performance. You can find their full list of quantized models on their huggingface repo: <a href="https://huggingface.co/unsloth">https://huggingface.co/unsloth</a></p><pre>from unsloth import FastLanguageModel<br>import torch<br>max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!<br>dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+<br>load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.<br><br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name = &quot;unsloth/Phi-3-mini-4k-instruct&quot;, # Unsloth automatically switches this to unsloth/Phi-3-mini-4k-instruct-bnb-4bit if load_in_4bit is True<br>    max_seq_length = max_seq_length,<br>    dtype = dtype,<br>    load_in_4bit = load_in_4bit,<br>    # token = &quot;hf_...&quot;, # use one if using gated models like meta-llama/Llama-2-7b-hf<br>)</pre><p>Output:</p><pre>🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.<br><br>Unsloth: You passed in `unsloth/Phi-3-mini-4k-instruct` and `load_in_4bit = True`.<br>We shall load `unsloth/Phi-3-mini-4k-instruct-bnb-4bit` for 4x faster loading.<br><br>config.json:   0%|          | 0.00/1.16k [00:00&lt;?, ?B/s]<br>==((====))==  Unsloth: Fast Mistral patching release 2024.5<br>   \\   /|    GPU: NVIDIA GeForce RTX 3080. Max memory: 9.999 GB. Platform = Linux.<br>O^O/ \_/ \    Pytorch: 2.2.0. CUDA = 8.6. CUDA Toolkit = 12.1.<br>\        /    Bfloat16 = TRUE. Xformers = 0.0.24. FA = False.<br> &quot;-____-&quot;     Free Apache license: http://github.com/unslothai/unsloth<br><br>model.safetensors:   0%|          | 0.00/2.26G [00:00&lt;?, ?B/s]<br>generation_config.json:   0%|          | 0.00/172 [00:00&lt;?, ?B/s]<br>tokenizer_config.json:   0%|          | 0.00/3.17k [00:00&lt;?, ?B/s]<br>tokenizer.model:   0%|          | 0.00/500k [00:00&lt;?, ?B/s]<br>added_tokens.json:   0%|          | 0.00/293 [00:00&lt;?, ?B/s]<br>special_tokens_map.json:   0%|          | 0.00/571 [00:00&lt;?, ?B/s]<br>tokenizer.json:   0%|          | 0.00/1.84M [00:00&lt;?, ?B/s]<br>Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.<br>Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.</pre><h4>Step 2: Add the LoRA adapters to the model</h4><p>This is PEFT after all, so we add LoRA adapters to train between 1–10%. Check out this explanation with sources from Perplexity AI if you need some reading on PEFT: <a href="https://www.perplexity.ai/search/describe-what-peft-Ts.4Wu7NStuFlo.3k.O6lQ#0">https://www.perplexity.ai/search/describe-what-peft-Ts.4Wu7NStuFlo.3k.O6lQ#0</a></p><p>Without this, it would not be feasible to train Phi3.</p><p>Many of the parameters are set to the default parameters Unsloth had set to quickly see if a 3080 could actually do PEFT.</p><pre>model = FastLanguageModel.get_peft_model(<br>    model,<br>    r = 16, # Choose any number &gt; 0 ! Suggested 8, 16, 32, 64, 128<br>    target_modules = [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;,<br>                      &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;,],<br>    lora_alpha = 16,<br>    lora_dropout = 0, # Supports any, but = 0 is optimized<br>    bias = &quot;none&quot;,    # Supports any, but = &quot;none&quot; is optimized<br>    # [NEW] &quot;unsloth&quot; uses 30% less VRAM, fits 2x larger batch sizes!<br>    use_gradient_checkpointing = &quot;unsloth&quot;, # True or &quot;unsloth&quot; for very long context<br>    random_state = 3407,<br>    use_rslora = False,  # We support rank stabilized LoRA<br>    loftq_config = None, # And LoftQ<br>)</pre><p>Output:</p><pre>Unsloth 2024.5 patched 32 layers with 32 QKV layers, 32 O layers and 32 MLP layers.</pre><h4>Step 3: Map the Data</h4><p>Phi3 follows the following chat template:</p><pre>&lt;s&gt;&lt;|user|&gt;<br>Hi!&lt;|end|&gt;<br>&lt;|assistant|&gt;<br>Hello! How are you?&lt;|end|&gt;<br>&lt;|user|&gt;<br>I&#39;m doing great! And you?&lt;|end|&gt;</pre><p>As such, we need to map our data to match this so that the model knows what’s what. Unsloth supports several templates for various LLMs if you want to fine tune other models. In the example, they used ShareGPT and the current Dolly Dataset is not formatted to match this so some data engineering is required. However, I figured someone already did this to match a conversation, which is why we use Philipp Schmid’s OpenAPI Style Dolly Dataset. From there, it’s just a matter of matching things up!</p><pre>from unsloth.chat_templates import get_chat_template<br><br>tokenizer = get_chat_template(<br>    tokenizer,<br>    chat_template = &quot;phi-3&quot;, # Supports zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth<br>    mapping = {&quot;role&quot; : &quot;role&quot;, &quot;content&quot; : &quot;content&quot;, &quot;user&quot; : &quot;user&quot;, &quot;assistant&quot; : &quot;assistant&quot;}, # ShareGPT style<br>)<br><br>def formatting_prompts_func(examples):<br>    convos = examples[&quot;messages&quot;]<br>    texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]<br>    return { &quot;text&quot; : texts, }<br>pass<br><br>from datasets import load_dataset<br>eval = load_dataset(&quot;philschmid/dolly-15k-oai-style&quot;, split = &quot;train&quot;)<br>eval = eval.train_test_split(test_size = 0.2)<br>eval = eval.map(formatting_prompts_func, batched = True,)</pre><p>Let’s double check if the mapping came out correctly!</p><pre>print(eval[5][&quot;text&quot;]) # see the function formatting_prompts_func above for the return value we are using</pre><p>Output:</p><pre>&lt;s&gt;&lt;|user|&gt;<br>If I have more pieces at the time of stalemate, have I won?<br>Stalemate is a situation in chess where the player whose turn it is to move is not in check and has no legal move. Stalemate results in a draw. During the endgame, stalemate is a resource that can enable the player with the inferior position to draw the game rather than lose. In more complex positions, stalemate is much rarer, usually taking the form of a swindle that succeeds only if the superior side is inattentive.[citation needed] Stalemate is also a common theme in endgame studies and other chess problems.<br><br>The outcome of a stalemate was standardized as a draw in the 19th century. Before this standardization, its treatment varied widely, including being deemed a win for the stalemating player, a half-win for that player, or a loss for that player; not being permitted; and resulting in the stalemated player missing a turn. Stalemate rules vary in other games of the chess family.&lt;|end|&gt;<br>&lt;|assistant|&gt;<br>No. <br>Stalemate is a drawn position. It doesn&#39;t matter who has captured more pieces or is in a winning position&lt;|end|&gt;</pre><p>Great! It matches the Phi3 chat template so we are good to move on.</p><h4>Step 4: Set up the Trainer</h4><p>Now we need to set up the spicy bit: the trainer. Unsloth is built ontop of huggingface’s library so we can reference hugginface’s library for SFTTrainer to understand the parameters it uses, particularly the TrainingArguments(). I have not done extensive research on finding optimal parameters (yet?) so many of these values are defaults from Unsloth. I did add an evaluation dataset and set load_best_model_at_end to True just in case.</p><pre>from trl import SFTTrainer<br>from transformers import TrainingArguments<br>from unsloth import is_bfloat16_supported<br><br>trainer = SFTTrainer(<br>    model = model,<br>    tokenizer = tokenizer,<br>    train_dataset = eval[&quot;train&quot;],<br>    eval_dataset = eval[&#39;test&#39;],<br>    dataset_text_field = &quot;text&quot;,<br>    max_seq_length = max_seq_length,<br>    dataset_num_proc = 2,<br>    packing = False, # Can make training 5x faster for short sequences.<br>    args = TrainingArguments(<br>        per_device_train_batch_size = 2,<br>        per_device_eval_batch_size = 2,<br>        gradient_accumulation_steps = 4,<br>        warmup_steps = 5,<br>        # max_steps = 60,<br>        num_train_epochs=5,<br>        learning_rate = 2e-4,<br>        fp16 = not is_bfloat16_supported(),<br>        bf16 = is_bfloat16_supported(),<br>        logging_steps = 1,<br>        optim = &quot;adamw_8bit&quot;,<br>        weight_decay = 0.01,<br>        lr_scheduler_type = &quot;linear&quot;,<br>        seed = 3407,<br>        output_dir = &quot;outputs&quot;,<br>        load_best_model_at_end=True,<br>        eval_strategy = &quot;steps&quot;,<br>        eval_steps= 60,<br>        save_strategy = &quot;steps&quot;,<br>        save_steps=60<br>    ),<br>)</pre><h4>Step 4a: Check your GPU Details</h4><p>Just in case, let’s make sure we can see my 3080</p><pre>gpu_stats = torch.cuda.get_device_properties(0)<br>start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)<br>max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)<br>print(f&quot;GPU = {gpu_stats.name}. Max memory = {max_memory} GB.&quot;)<br>print(f&quot;{start_gpu_memory} GB of memory reserved.&quot;)</pre><p>Output:</p><pre>GPU = NVIDIA GeForce RTX 3080. Max memory = 9.999 GB.<br>3.33 GB of memory reserved.</pre><h4><strong>Step 5: Training</strong></h4><p>Time to train! Let’s RIDE!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*JiiEDrcj6OyVlmHu.gif" /></figure><pre>trainer_stats = trainer.train()</pre><h4>Step 6: Results</h4><p>I definitely should not have used 5 epochs with a Batch size per device of 2. It took way too long but it did COMPLETE! That’s a win in my book.</p><p>Here’s the output of the job. I’ve truncated the outputs to show some of the checkpoints at the beginning and at the end. You can see the full list at the end of the article:</p><pre>==((====))==  Unsloth - 2x faster free finetuning | Num GPUs = 1<br>   \\   /|    Num examples = 12,008 | Num Epochs = 5<br>O^O/ \_/ \    Batch size per device = 2 | Gradient Accumulation steps = 4<br>\        /    Total batch size = 8 | Total steps = 7,505<br> &quot;-____-&quot;     Number of trainable parameters = 29,884,416<br><br>7505/7505 12:50:20, Epoch 5/5]<br>Step Training Loss Validation Loss<br>60 1.677900 1.568713<br>120 1.713000 1.556613<br>180 1.674900 1.555526<br>240 1.294100 1.552386<br><br>...<br><br>7140 0.488800 1.818021<br>7200 1.236400 1.812761<br>7260 0.866100 1.810694<br>7320 0.854400 1.814482<br>7380 1.160400 1.815786<br>7440 0.901600 1.815607<br>7500 0.834400 1.814518</pre><p>Well it looks like it ended up overfitting at the end since the training loss decreased but the validation loss increased. Again, probably shouldn’t have randomly picked 5 epochs. At least I used load_best_model_at_end!</p><p>Here are some of the stats of the training job:</p><pre>used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)<br>used_memory_for_lora = round(used_memory - start_gpu_memory, 3)<br>used_percentage = round(used_memory         /max_memory*100, 3)<br>lora_percentage = round(used_memory_for_lora/max_memory*100, 3)<br>print(f&quot;{trainer_stats.metrics[&#39;train_runtime&#39;]} seconds used for training.&quot;)<br>print(f&quot;{round(trainer_stats.metrics[&#39;train_runtime&#39;]/60, 2)} minutes used for training.&quot;)<br>print(f&quot;Peak reserved memory = {used_memory} GB.&quot;)<br>print(f&quot;Peak reserved memory for training = {used_memory_for_lora} GB.&quot;)<br>print(f&quot;Peak reserved memory % of max memory = {used_percentage} %.&quot;)<br>print(f&quot;Peak reserved memory for training % of max memory = {lora_percentage} %.&quot;)</pre><p>Output:</p><pre>46221.8864 seconds used for training. #12.8 hours<br>770.36 minutes used for training.<br>Peak reserved memory = 7.787 GB.<br>Peak reserved memory for training = 4.457 GB.<br>Peak reserved memory % of max memory = 77.878 %.<br>Peak reserved memory for training % of max memory = 44.574 %.</pre><h4>Step 7: Evaluation</h4><p>Ok! So evaluating the output of an LLM has been an extremely hot topic, with a lot of discourse on whether the current evaluation benchmarks like MMLU or ARC makes sense if we are trying to determine what a human would like to see. So, I asked a few friends on which model output they preferred and, maybe they were being nice, but they liked mine the most! What really stood out to me was that the fine tuned version followed Few Shot Prompting much better than the original model.</p><p>We followed Unsloth’s recommended way of running inference on the model which was replicated to run the original, not fine tuned model to compare outputs.</p><pre>#This is the fine tuned version<br>from unsloth.chat_templates import get_chat_template<br><br>tokenizer = get_chat_template(<br>    tokenizer,<br>    chat_template = &quot;phi-3&quot;, # Supports zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth<br>    mapping = {&quot;role&quot; : &quot;role&quot;, &quot;content&quot; : &quot;content&quot;, &quot;user&quot; : &quot;user&quot;, &quot;assistant&quot; : &quot;assistant&quot;}, # ShareGPT style<br>)<br><br>FastLanguageModel.for_inference(model) # Enable native 2x faster inference<br><br><br>email_summary = f&quot;Summarize the email below the - and classify it as positive, negative or neutral\n-\nAhead of your interview, we want to send a friendly reminder of some best practices for the interview process. These are aimed at protecting you, your current or former employer(s), and Company: We do not want (and please do not bring to Company) any trade secret or confidential information from your current or any prior employer! Remember that if you created anything during your time as an employee at your current or former employer, that employer likely owns it. Please don’t bring or share with Company anything owned by your current or prior employer. If you’re creating any documents for Company (e.g. candidate assignment or presentation), do not use your current work computer and/or any materials from your current employer. If you visit any Company office, do not bring your work computer. No matter what, please avoid connecting your work computer to any Company’s Wi-Fi network. Do not forward any information from your current or prior employer to Company. While you’re still employed elsewhere, do not attend internal Company events. Lastly, review your current employment contract to understand whether it contains provisions such as a non-compete or non-solicitation clause. In the meantime, please let me know if you have any questions, technical difficulties, or need any accommodations throughout the interview process. We look forward to meeting you\n-\nYour output should look like the examples below:\nExample:\nCategory: Neutral\nCategory: Positive&quot;<br><br>messages = [<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: email_summary},<br>]<br><br>inputs = tokenizer.apply_chat_template(<br>    messages,<br>    tokenize = True,<br>    add_generation_prompt = True, # Must add for generation<br>    return_tensors = &quot;pt&quot;,<br>).to(&quot;cuda&quot;)<br><br>outputs = model.generate(input_ids = inputs, max_new_tokens = 1000, use_cache = False)<br>tokenizer.batch_decode(outputs)</pre><p><strong>Original Full Model Output:</strong></p><p>&lt;s&gt;&lt;|user|&gt; Summarize the email below the — and classify it as positive, negative or neutral<br>-<br>Summarize the email below the — and classify it as positive, negative or neutral<br>-<br>Ahead of your interview, we want to send a friendly reminder of some best practices for the interview process. These are aimed at protecting you, your current or former employer(s), and company: We do not want (and please do not bring to company) any trade secret or confidential information from your current or any prior employer! Remember that if you created anything during your time as an employee at your current or former employer, that employer likely owns it. Please don’t bring or share with company anything owned by your current or prior employer. If you’re creating any documents for company (e.g. candidate assignment or presentation), do not use your current work computer and/or any materials from your current employer. If you visit any company office, do not bring your work computer. No matter what, please avoid connecting your work computer to any company’ Wi-Fi network. Do not forward any information from your current or prior employer to company. While you’re still employed elsewhere, do not attend internal company events. Lastly, review your current employment contract to understand whether it contains provisions such as a non-compete or non-solicitation clause. In the meantime, please let me know if you have any questions, technical difficulties, or need any accommodations throughout the interview process. We look forward to meeting you<br>-<br>Your output should look like the examples below:<br>Example:<br>Category: Neutral<br>Category: Positive</p><p>&lt;|end|&gt;</p><p>&lt;|assistant|&gt; Category: Neutral<br>The given email serves as a reminder of best practices for the interview process. It aims to safeguard the participant, their current/former employer, and Company by prohibiting the sharing of trade secrets, confidential information, or work-related materials. The email advises canindates not to connect their current employer’s work computer to Company’s WiFi…</p><p>&lt;|end|&gt;</p><p><strong>Fine Tuned Output:</strong></p><p>&lt;s&gt;&lt;|user|&gt; Summarize the email below the — and classify it as positive, negative or neutral<br>-<br>Ahead of your interview, we want to send a friendly reminder of some best practices for the interview process. These are aimed at protecting you, your current or former employer(s), and company: We do not want (and please do not bring to company) any trade secret or confidential information from your current or any prior employer! Remember that if you created anything during your time as an employee at your current or former employer, that employer likely owns it. Please don’t bring or share with company anything owned by your current or prior employer. If you’re creating any documents for company (e.g. candidate assignment or presentation), do not use your current work computer and/or any materials from your current employer. If you visit any company office, do not bring your work computer. No matter what, please avoid connecting your work computer to any company’ Wi-Fi network. Do not forward any information from your current or prior employer to company. While you’re still employed elsewhere, do not attend internal company events. Lastly, review your current employment contract to understand whether it contains provisions such as a non-compete or non-solicitation clause. In the meantime, please let me know if you have any questions, technical difficulties, or need any accommodations throughout the interview process. We look forward to meeting you<br>-<br>Your output should look like the examples below:<br>Example:<br>Category: Neutral<br>Category: Positive</p><p>&lt;|end|&gt;</p><p>&lt;|assistant|&gt; Category: Neutral&lt;|end|&gt;</p><p>There are absolutely some best practices in prompting that I’m missing here but I would argue that, while both models were accurate in describing that block of text as neutral, the fine tuned model matched exactly the examples I provided while the original model was extremely verbose. I cut out the full answer since it was just more explaining of what the text was saying.</p><p>None of this is very scientific and is just me trying a few different inputs out. I’m still figuring out the best way to evaluation this so this is definitely a work in progress. But not too shabby!</p><p>Check out my models below at my huggingface repo: <a href="https://huggingface.co/auchoi">https://huggingface.co/auchoi</a></p><h3>Key Takeaways</h3><p>Wow, that was a lot easier than I thought. Seriously, big thank you to Unsloth for creating a simple and powerful framework for average people like me to use! If PEFT can deliver improvements like this, I can only imagine what a full fine-tuning job would look like knowing that a full job will perform significantly better than a PEFT job (see paper: <a href="https://arxiv.org/abs/2405.09673">LoRA Learns Less and Forgets Less</a>)</p><p>But this exercise did teach me a few things:</p><ol><li>This took 12.8 hours of “very high” electricity usage from the 3080, who has a max wattage of 350W. Considering my thermostat went from 72 to 78 when it was 60 Fahrenheit outside, this will definitely be adding some $$$ to my electricity bill.</li><li>There’s still so much to learn to better optimize this training. New research is still coming out on what could potentially be the best way to do fine training.</li><li>Data is hard. The groups training these models will 100% have tapped into the open source datasets. As an individual working on this, it’s hard to make a similar quality dataset of this size to practice this fine tuning. It may be insignificant in the grand scheme of things but it weighed on me throughout the training process.</li><li>Merging the LoRA adapters to Float16 and 4bit caused the model to degrade in performance, reverting back much of what it learned to the original model’s behavior. Loading the LoRA adapters separately maintained the behavior I was looking for</li></ol><p>There’s so much to learn but we have come so far in a year. If you’re looking to fail fast and break all these LLMs with random data across the internet, now is the time!</p><p>I hope the article proved to be insightful in the tools and capabilities we have accessible to us today. I welcome and greatly appreciate any feedback from anyone and everyone as this was the first LLM I successfully fine tuned without relying a cloud service.</p><p>Thanks for reading! <br><a href="https://www.linkedin.com/in/austin-choi-18867abb/">https://www.linkedin.com/in/austin-choi-18867abb/</a><br>Austin Choi</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfd3b88e30ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>