<?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 Sherlock Xu on Medium]]></title>
        <description><![CDATA[Stories by Sherlock Xu on Medium]]></description>
        <link>https://medium.com/@sherlockxu?source=rss-45268e99b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aCgWxGZnbTvCjwfbFtHvIg.jpeg</url>
            <title>Stories by Sherlock Xu on Medium</title>
            <link>https://medium.com/@sherlockxu?source=rss-45268e99b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 24 Apr 2026 15:22:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sherlockxu/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[A Guide to Model Composition]]></title>
            <link>https://medium.com/bentoml/a-guide-to-model-composition-09fbff8e62a5?source=rss-45268e99b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/09fbff8e62a5</guid>
            <category><![CDATA[composition-model]]></category>
            <category><![CDATA[bentoml]]></category>
            <category><![CDATA[bentocloud]]></category>
            <category><![CDATA[compound-ai-system]]></category>
            <dc:creator><![CDATA[Sherlock Xu]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 08:18:02 GMT</pubDate>
            <atom:updated>2024-07-30T08:18:02.083Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post was originally published at <em>The New Stack: </em><a href="https://thenewstack.io/a-guide-to-model-composition/">https://thenewstack.io/a-guide-to-model-composition/</a></p><p>Consider an AI-powered image recognition app designed to identify and classify wildlife photos. You upload a picture taken during a hike, and within moments, the app not only identifies the animal in the photo but also provides detailed information about its species, habitat, and conservation status. This kind of app can be built through <strong>model composition</strong> — a technique where multiple AI models collaborate to analyze and interpret the image from various perspectives.</p><p>Model composition in this context might involve a sequence of specialized models: one for detecting the animal in the image, another for classifying it into broad categories (e.g., bird, mammal, and reptile), and yet another set of models that work together to determine the specific species. This layered approach offers a nuanced analysis that exceeds the capabilities of a single AI model.</p><h3>What is model composition?</h3><p>At its core, model composition is a strategy in machine learning that combines multiple models to solve a complex problem that cannot be easily addressed by a single model. This approach leverages the strengths of each individual model, providing more nuanced analyses and improved accuracy. Model composition can be seen as assembling a team of experts, where each member brings specialized knowledge and skills to the table, working together to achieve a common goal.</p><p>Many real-world problems are too complicated for a one-size-fits-all model. By orchestrating multiple models, each trained to handle specific aspects of a problem or data type, we can create a more comprehensive and effective solution.</p><p>There are several ways to implement model composition, including but not limited to:</p><ul><li><strong>Sequential processing</strong>: Models are arranged in a pipeline, where the output of one model serves as the input for the next. This is often used in tasks like data preprocessing, feature extraction, and then classification or prediction.</li><li><strong>Parallel processing</strong>: Multiple models run in parallel, each processing the same input independently. Their outputs are then combined, either by averaging, voting, or through a more complex aggregation model, to produce a final result. This is commonly used in ensemble methods.</li></ul><p>An important concept related to model composition is the <strong>inference graph</strong>. An inference graph visually represents the flow of data through various models and processing steps in a model composition system. It outlines how models are connected, the dependencies between them, and how data transforms and flows from input to final prediction. The graphical representation helps us design, implement, and understand complex model composition. Here is an inference graph example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3cc03hvb8ekwcYNJ" /></figure><ol><li>The service accepts a text input, such as “I have an idea!”</li><li>It simultaneously sends the prompt to three separate text generation models, which run in parallel to produce results using different algorithms or datasets.</li><li>The results from these three models are then sent to a text classification model.</li><li>The classification model assesses each piece of generated text and assigns a classification score to them (for example, based on the content’s sentiment).</li><li>Finally, the service aggregates the generated text along with their respective classification scores and returns them as JSON.</li></ol><h3>When should I compose models?</h3><p>Model composition is a practical solution to a wide array of challenges in machine learning. Here are some key use cases where model composition plays a crucial role.</p><h4>Multi-modal applications</h4><p>In today’s digital world, data comes in various forms: text, images, audio, and more. A multi-modal application combines models specialized in processing different types of data. A typical example of composing models to create multi-modal applications is <a href="https://arxiv.org/abs/2301.12597">BLIP-2</a>, which is designed for tasks that involve both text and images.</p><p>BLIP2 integrates three distinct models, each providing a unique capability to the system:</p><ul><li>A frozen large language model (LLM): Provides strong language generation and zero-shot transfer abilities.</li><li>A frozen pre-trained image encoder: Extracts and encodes visual information from images.</li><li>A lightweight Querying Transformer model (Q-Former): Bridges the modality gap between the LLM and the image encoder. It integrates visual information from the encoder with the LLM, focusing on the most relevant visual details for generating text.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kKAE_Zv4TXbGpxtI" /><figcaption>BLIP-2 architecture. Source: <a href="https://arxiv.org/abs/2301.12597">The original BLIP-2 paper</a></figcaption></figure><h4>Ensemble modeling</h4><p>Ensemble modeling is a technique used to improve the prediction of machine learning models. It does so by combining the predictions from multiple models to produce a single, more accurate result. The core idea is that by aggregating the predictions of several models, you can often achieve better performance than any single model could on its own. The models in an ensemble may be of the same type (e.g., all decision trees) or different types (e.g., a combination of neural networks, decision trees, and logistic regression models). Key techniques in ensemble modeling include:</p><ul><li><strong>Bagging</strong>: Train multiple models on different subsets of the training data and then average their predictions, useful for reducing variance.</li><li><strong>Boosting</strong>: Sequentially train models, where each model attempts to correct errors made by the previous ones.</li><li><strong>Stacking</strong>: Train multiple models and then use a better model that leverages the strengths of each base model to improve overall performance and combine their predictions.</li></ul><p>A real-world use case of ensemble modeling is a weather forecasting system, where accuracy is important for planning and safety across industries and activities. An ensemble model for weather prediction might integrate outputs from various models, each trained on different data sets, using different algorithms, or focusing on different aspects of weather phenomena. Some models might be more capable of predicting precipitation, while others perform better at forecasting temperature or wind speed. By aggregating these predictions, an ensemble approach can provide a more accurate and nuanced forecast.</p><h4>Pipeline processing</h4><p>Machine learning tasks often require a sequence of processing steps to transform raw data into actionable insights. Implementing model composition can help you structure these tasks as pipelines, where each step is handled by a different model optimized for a specific function.</p><p>One of the common use cases is an automated document analysis system, capable of processing, understanding, and extracting meaningful information from documents. The system might use a series of models, each dedicated to a phase in the processing pipeline:</p><ul><li><strong>Preprocessing</strong>: The first step might require an OCR (Optical Character Recognition) model that extracts text from scanned documents or images. This model is specialized in recognizing and converting varied fonts and handwriting styles into machine-readable text.</li><li><strong>Prediction</strong>: Following text extraction, a text classification model can be used to categorize the document based on its content, such as a legal document, a technical manual, and a financial report. This classification step is important for routing the document to appropriate downstream processes.</li><li><strong>Post-processing</strong>: After classification, a summarization model can be used to generate a concise summary of the document’s content. This summary provides quick insights into the document, informing decision-making and prioritization.</li></ul><p>In addition to sequential pipelines, you can also implement parallel processing for multiple models to run concurrently on the same data (as shown in the first image). This is useful in scenarios like:</p><ul><li><strong>Ensemble modeling</strong>: Predictions from multiple models are aggregated to improve accuracy.</li><li><strong>Computer vision tasks</strong>: Models for image segmentation and object detection may run in parallel to provide a comprehensive analysis of an image, combining insights into the image’s structure with identification of specific objects.</li></ul><h3>What are the benefits of model composition?</h3><p>Model composition provides a number of operational and developmental advantages. Here are some key benefits:</p><h4>Improved accuracy and performance</h4><p>In some cases, the synergy of multiple models working together can result in improved accuracy and performance. Each model in the composition may focus on a specific aspect of the problem, such as different data types or particular features of the data, ensuring that the combined system covers the entire problem space than any single model could. This is especially true in ensemble modeling, as aggregating the results from multiple models can help cancel out their individual biases and errors, leading to more accurate predictions.</p><h4>Dedicated infrastructure and resource allocation</h4><p>Model composition allows you to deploy the involved models across varied hardware devices, optimizing the use of computational resources. They can be assigned to run on the most appropriate infrastructure — whether it’s CPU, GPU, or edge devices — based on their processing needs and the availability of resources. This dedicated allocation also ensures that each part of the system can be scaled separately.</p><h4>Customization and flexibility</h4><p>One of the most significant advantages of model composition is the flexibility it offers. Models can be easily added, removed, or replaced within the system, allowing developers to adapt and evolve their applications as new technologies emerge or as the requirements change. This modular approach simplifies updates and maintenance, ensuring that the system can quickly adapt to new challenges and opportunities.</p><h4>Faster development and iteration</h4><p>Model composition supports a parallel development workflow, where teams can work on different models or components of the system simultaneously. This helps accelerate the development process, which means quicker iterations and more rapid prototyping. It also enables teams to provide more agile responses to feedback and changing requirements, as individual models can be refined or replaced without disrupting the entire system.</p><h4>Resource optimization</h4><p>By intelligently distributing workloads across multiple models, each optimized for specific tasks or hardware, you can maximize resource utilization. This optimization can lead to more efficient processing, reduced latency, and lower operational costs, particularly in complex applications that require substantial computational power. Effective resource optimization also means that your application can scale more gracefully, accommodating increases in data volume or user demand.</p><h3>Composing multiple models with BentoML</h3><p>Different model serving or deployment frameworks may adopt different approaches to model composition. In this connection, <a href="https://github.com/bentoml/BentoML">BentoML</a>, an open-source model serving framework, provides simple service APIs to help you wrap models, establish interservice communication, and expose the composed models as REST API endpoints.</p><p>The code example below demonstrates how to use BentoML to compose multiple models. In BentoML, each Service is defined as a Python class. You use the @bentoml.service decorator to mark it as a Service and allocate CPU or GPU resources to it. When you deploy it to <a href="https://link.bentoml.com/bentocloud-a-guide-to-model-composition">BentoCloud</a>, different Services can run on dedicated instance types and be separately scaled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*FuKZ4SfaCJ6CfPIb" /></figure><p>In this BentoML service.py file, GPT2 and DistilGPT2 are initialized as separate BentoML Services to generate text. The BertBaseUncased Service then takes the generated text and classifies it, providing a score that represents sentiment. The InferenceGraph Service orchestrates these individual Services, using asyncio.gather to concurrently generate text from both GPT-2 models and then classifying the output using the BERT model.</p><p>After deployed to BentoCloud, Services can run on separate instance types as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CVjRgHPqvHWVExLi" /></figure><p>Monitor the performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*omFMSd1hqIhopNKC" /></figure><p>For detailed explanations, see<a href="https://github.com/bentoml/BentoML/tree/main/examples/inference_graph"> this example project</a>.</p><h3>Frequently asked questions</h3><p>Before I wrap up, let’s see some frequently asked questions about model composition.</p><h4>What is the difference between ensemble modeling and multi-modal applications?</h4><p>These two machine learning concepts serve different purposes and are applied in different contexts.</p><ul><li><strong>Purpose and application:</strong> Ensemble modeling improves prediction accuracy by combining multiple models. Multi-modal applications integrate and interpret data from multiple sources or types to make better decisions or predictions.</li><li><strong>Models vs. Data:</strong> Ensemble modeling focuses on using multiple models to enhance predictions. Multi-modal applications focus on integrating different types of data (e.g., text, image, audio).</li><li><strong>Implementation</strong>: Multi-modal systems often require data preprocessing and feature extraction techniques to handle different data types effectively. Ensemble modeling, on the other hand, needs strategies for combining model predictions, which might involve direct averaging or more complicated voting systems.</li></ul><h4>I am using a single model for my application. Should I move to multiple models?</h4><p>It’s important to note that while model composition offers different benefits as mentioned above, it’s not always necessary. If a single model can efficiently and accurately accomplish the task at hand, I recommend you just stick with it. The decision to compose multiple models and the design of the processing pipeline should be guided by your specific requirements.</p><h4>How does model composition affect production deployment?</h4><p>The integration of multiple models into a single application affects production deployment in several key ways:</p><p>Increased complexity</p><ul><li><strong>Configuration and management</strong>: Each model in the composition may require its configuration, dependencies, and environment. Managing them across multiple models adds complexity to the deployment process.</li><li><strong>Service orchestration</strong>: Composing multiple models often requires careful orchestration to ensure that data flows correctly between models and that each model is executed in the correct order or in parallel as required.</li></ul><p>Resource allocation</p><ul><li><strong>Hardware requirements</strong>: As mentioned above, different models may have different hardware requirements. Some models might need GPUs for inference, while others can run on CPUs. The serving and deployment framework you select should support flexible resource allocation to meet the needs.</li><li><strong>Scaling strategies</strong>: Scaling multiple models in production may not be as straightforward as scaling a single model. Different components of the application may have varying loads, requiring dynamic scaling strategies that can adjust resources for individual models based on demand.</li></ul><p>Monitoring and maintenance</p><ul><li><strong>Monitoring</strong>: Keeping track of the performance and health of different models in production requires comprehensive monitoring solutions that can provide insights into each model’s performance, resource usage, and potential bottlenecks.</li><li><strong>Versioning and updates</strong>: Updating one model in a composite application can have cascading effects on other models. Proper version control and testing strategies must be in place to manage updates without disrupting the application’s overall performance.</li></ul><p>Deployment strategies</p><ul><li><strong>Microservices architecture</strong>: Adopting a microservices architecture can simplify the deployment of multiple models by encapsulating each model as a separate service. This approach simplifies scaling, updates, and management but requires flexible service orchestration tools.</li><li><strong>Containerization</strong>: Using containers for deploying AI models can help manage dependencies and environments for each model. Container orchestration tools like Kubernetes can help manage the deployment, scaling, and networking of containerized models.</li></ul><p>Model composition can affect deployment by requiring more resources and potentially more complex deployment strategies. However, as shown in the example above, platforms like BentoML and BentoCloud can help developers build AI applications of multiple models by allowing them to package, deploy, and scale multi-model services efficiently.</p><h3>Final thoughts</h3><p>While the benefits of model composition are clear, from enhanced performance to the ability to process multiple data types, it’s important to acknowledge the complexity it introduces, especially related to production deployment. Successful implementation requires careful planning, resource management, and the adoption of modern deployment practices and tools to navigate the challenges of configuration, scaling, and maintenance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09fbff8e62a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentoml/a-guide-to-model-composition-09fbff8e62a5">A Guide to Model Composition</a> was originally published in <a href="https://medium.com/bentoml">BentoML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving A LlamaIndex RAG App as REST APIs]]></title>
            <link>https://medium.com/@sherlockxu/serving-a-llamaindex-rag-app-as-rest-apis-4b2cdb93e925?source=rss-45268e99b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b2cdb93e925</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[bentocloud]]></category>
            <category><![CDATA[llamaindex]]></category>
            <category><![CDATA[bentoml]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Sherlock Xu]]></dc:creator>
            <pubDate>Tue, 28 May 2024 11:03:59 GMT</pubDate>
            <atom:updated>2024-05-28T11:05:32.215Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating REST APIs for a retrieval-augmented generation (RAG) system provides a flexible and scalable way to integrate RAG with a wide range of applications. In this blog post, we will cover the basics of how to serve a RAG system built with <a href="https://github.com/run-llama/llama_index">LlamaIndex</a> as REST APIs using <a href="https://github.com/bentoml/BentoML">BentoML</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhFmbzO5KHaWHLcEhvgDig.jpeg" /></figure><p>This is Part 1 of our blog series on Private RAG Deployment with BentoML. You will progressively build upon an example RAG app and expand to a fully private RAG system with open-source and custom fine-tuned models. Topics to cover in the blog series:</p><ul><li>Part 1: Serving A LlamaIndex RAG App as REST APIs</li><li>Part 2: Self-Hosting LLMs and Embedding Models for RAG</li><li>Part 3: Multi-Model Orchestration for Advanced RAG systems</li></ul><h3>Concepts</h3><p>Before we serve the RAG service, let’s briefly introduce RAG and LlamaIndex.</p><h4>RAG</h4><p>Simply put, RAG is designed to help LLMs provide better answers to queries by equipping them with a customized knowledge base. This allows them to return relevant information even if it hasn’t been trained directly on that data. Here’s a brief overview of how a typical RAG system operates:</p><ol><li>The RAG system breaks the input data into manageable chunks.</li><li>An embedding model translates these chunks into vectors.</li><li>These vectors are stored in a database, ready for retrieval.</li><li>Upon receiving a query, the RAG system retrieves the most relevant chunks based on their vector similarities to the query.</li><li>The LLM synthesizes the retrieved information to generate a contextually relevant response.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g0iDdRb_HEXoicb6.png" /><figcaption>Image source: <a href="https://gradientflow.com/techniques-challenges-and-future-of-augmented-language-models/">Techniques, Challenges, and Future of Augmented Language Models</a></figcaption></figure><p>For more information about RAG, you can refer to our previous articles.</p><ul><li><a href="https://www.bentoml.com/blog/understanding-retrieval-augmented-generation-part-1">Understanding Retrieval-Augmented Generation: Part 1</a></li><li><a href="https://www.bentoml.com/blog/understanding-retrieval-augmented-generation-part-2">Understanding Retrieval-Augmented Generation: Part 2</a></li><li><a href="https://www.bentoml.com/blog/building-rag-with-open-source-and-custom-ai-models">Building RAG with Open-Source and Custom AI Models</a></li></ul><h4>LlamaIndex</h4><p><a href="https://github.com/run-llama/llama_index">LlamaIndex</a> is a Python library that enhances the capabilities of LLMs by integrating custom data sources, such as APIs and documents. It provides efficient data ingestion, indexing, and querying, making it an ideal tool for building compound Python programs like RAG. Therefore, we will use it together with BentoML across this RAG blog series.</p><h3>What are we building?</h3><p>Production use cases often require an API serving system to expose your RAG code. Although web frameworks can help, they become limiting as you start adding model inference components to your server. For more information, see <a href="https://www.bentoml.com/blog/building-rag-with-open-source-and-custom-ai-models">Building RAG with Open-Source and Custom AI Models</a>.</p><p>In this blog post, we will be building a REST API service with an /ingest_text endpoint for knowledge ingestion and a /query endpoint for handling user queries. The /ingest_text API lets you submit a text file to populate your RAG system&#39;s knowledge base so that you can interact with the /query API to answer questions.</p><h3>Setting up the environment</h3><p>You can find all the source code of this blog series in the <a href="https://github.com/bentoml/rag-tutorials">bentoml/rag-tutorials</a> repo. Clone the entire project and go to the 01-simple-rag directory.</p><pre>git clone https://github.com/bentoml/rag-tutorials.git<br>cd rag-tutorials/01-simple-rag</pre><p>We recommend you create a virtual environment to manage dependencies and avoid conflicts with your local environment:</p><pre>python -m venv rag-serve<br>source rag-serve/bin/activate</pre><p>Install all the dependencies.</p><pre>pip install -r requirement.txt</pre><p>By default, LlamaIndex use OpenAI’s text embedding model and large language model APIs. Set your OpenAI API key as an environment variable to allow your RAG to authenticate with OpenAI’s services.</p><pre>export OPENAI_API_KEY=&quot;your_openai_key_here&quot;</pre><h3>Serving a LlamaIndex RAG service</h3><p>First, let’s define a class for indexing documents using the LlamaIndex framework:</p><pre># Define a directory to persist index data<br>PERSIST_DIR = &quot;./storage&quot;<br><br>class RAGService:<br><br>    def __init__(self):<br>        # Set OpenAI API key from environment variable<br>        openai.api_key = os.environ.get(&quot;OPENAI_API_KEY&quot;)<br><br>        from llama_index.core import Settings<br>        # Configure text splitting to parse documents into smaller chunks<br>        self.text_splitter = SentenceSplitter(chunk_size=1024, chunk_overlap=20)<br>        Settings.node_parser = self.text_splitter<br><br>        # Initialize an empty index<br>        index = VectorStoreIndex.from_documents([])<br>        # Persist the empty index initially<br>        index.storage_context.persist(persist_dir=PERSIST_DIR)<br>        # Load index from storage if it exists<br>        storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)<br>        self.index = load_index_from_storage(storage_context)</pre><p><strong>Note</strong>: You can find the complete source code <a href="https://github.com/bentoml/rag-tutorials/blob/main/01-simple-rag/service.py">here</a> and we will only focus on the core snippets in this article. The code uses local storage for demo purpose and it is not scalable. You will need to integrate a vector database, such as Milvus, Pinecone, or Weaviate, for better performance at scale.</p><p>In the above code:</p><ul><li>VectorStoreIndex and StorageContext manage the storage and retrieval of indexed data.</li><li>SentenceSplitter breaks down the text into manageable chunks for better indexing and retrieval.</li></ul><p>Next, define a function for the RAG system to receive documents, which will be indexed and stored, and another one that responds to user queries by retrieving relevant information from the indexed data.</p><pre>    def ingest_text(self, txt) -&gt; str:<br>        # Create a Document object from the text<br>        with open(txt) as f:<br>            text = f.read()<br><br>        doc = Document(text=text)<br>        self.index.insert(doc)<br>        # Persist changes to the index<br>        self.index.storage_context.persist(persist_dir=PERSIST_DIR)<br>        return &quot;Successfully Loaded Document&quot;<br>        <br>    def query(self, query: str) -&gt; str:<br>        query_engine = self.index.as_query_engine()<br>        response = query_engine.query(query)<br>        return str(response)</pre><p>To test this class, simply create a RAGService object and call the methods.</p><pre># Instantiate the RAGService<br>rag_service = RAGService()<br><br># Ingest text from a file<br>ingest_result = rag_service.ingest_text(&quot;path/to/your/file.txt&quot;)<br>print(ingest_result)  # Expected output: &quot;Successfully Loaded Document&quot;<br><br># Query for information<br>query_result = rag_service.query(&quot;Your query question goes here&quot;)<br>print(query_result)  # Expected output: Retrieved information based on the query</pre><p>The code should work well and the next step is to create an API for ingesting knowledge and another one for asking questions. This is where BentoML comes in.</p><p>BentoML generates API endpoints based on function names, type hints, and uses them as callback functions to handle incoming API requests and produce responses. To serve this LlamaIndex app as an API server with BentoML, you only need to add a few decorators:</p><pre>PERSIST_DIR = &quot;./storage&quot;<br>        <br># Mark a class as a BentoML Service via decorator<br>@bentoml.service<br>class RAGService:<br><br>    def __init__(self):<br>        ...<br><br>    # Generate a REST API from the callback function<br>    @bentoml.api<br>    def ingest_text(self, txt: Annotated[Path, bentoml.validators.ContentType(&quot;text/plain&quot;)]) -&gt; str:<br>        ...<br><br>    # Generate a REST API from the callback function<br>    @bentoml.api<br>    def query(self, query: str) -&gt; str:<br>        ...</pre><p><strong>Note</strong>: See <a href="https://docs.bentoml.com/en/latest/guides/services.html">the BentoML Services doc</a> to learn more about @bentoml.service and @bentoml.api.</p><p>Start this BentoML Service by running:</p><pre>$ bentoml serve service:RAGService<br><br>2024-04-26T08:49:13+0000 [INFO] [cli] Starting production HTTP BentoServer from &quot;service:RAGService&quot; listening on http://localhost:3000 (Press CTRL+C to quit)</pre><p>The server is now accessible at <a href="http://localhost:3000.">http://localhost:3000</a>.</p><h3>Querying the RAG API service</h3><p>To begin querying your RAG APIs, create an <a href="https://docs.bentoml.com/en/latest/guides/clients.html">API client</a> and <a href="https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt">ingest a file</a> into your RAG system with the ingest_text API:</p><pre>import bentoml<br>from pathlib import Path<br><br>with bentoml.SyncHTTPClient(&quot;http://localhost:3000&quot;) as client:<br>    result = client.ingest_text(<br>        txt=Path(&quot;paul_graham_essay.txt&quot;),<br>    )</pre><p>Now, the text content of paul_graham_essay.txt has been chunked and embedded in your RAG system. Try submitting a query to ask a question about this document:</p><pre>import bentoml<br><br>with bentoml.SyncHTTPClient(&quot;http://localhost:3000&quot;) as client:<br>    result: str = client.query(<br>        query=&quot;What did Paul Graham do growing up?&quot;,<br>    )<br>    print(result)</pre><p>Example output:</p><pre>Paul Graham spent a lot of time at the Carnegie Institute as a kid and visited it in 1988. While looking at a painting there, he realized that paintings were something that could last and be made by individuals. This realization sparked his interest in art and the possibility of becoming an artist.</pre><p>BentoML generates a standard REST API server. You may choose to use any HTTP API client to interact with the endpoint. For example, you can send requests via curl:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pgtClu9xA7mPNxNg.gif" /></figure><h3>Deploying the RAG service for production</h3><p>Now, you can deploy this RAG app for production, which means it will be running in a scalable and reliable environment to handle real-world usage and traffic. Before deployment, create a bentofile.yaml file (already in <a href="https://github.com/bentoml/rag-tutorials/blob/main/01-simple-rag/bentofile.yaml">the project directory</a>) to set runtime configurations for your RAG. They will be packaged as a standardized distribution archive in BentoML, or a Bento. All the build options can <a href="https://docs.bentoml.com/en/latest/guides/build-options.html">be found here</a>. Remember to set the OPENAI_API_KEY environment variable.</p><pre>service: &quot;service.py:RAGService&quot;<br>labels:<br>  owner: bentoml-team<br>include:<br>  - &quot;*.py&quot;<br>exclude:<br>  - &quot;storage/&quot;<br>python:<br>  requirements_txt: &quot;./requirement.txt&quot;<br>docker:<br>  distro: debian<br>envs:<br>  - name: OPENAI_API_KEY<br>    value: &quot;sk-*******************&quot; # Add your key here</pre><p>You can then choose to deploy the LlamaIndex RAG app with Docker or BentoCloud.</p><h4>Docker</h4><p>Use bentoml build to build a Bento.</p><pre>bentoml build</pre><p>Make sure <a href="https://docs.docker.com/engine/install/">Docker</a> is running and then run the following command:</p><pre>bentoml containerize rag_service:latest</pre><p>Verify that the Docker image has been created successfully.</p><pre>$ docker images<br><br>REPOSITORY                     TAG                IMAGE ID       CREATED          SIZE<br>rag_service                    73ikq6ayikzzze5l   0bb88768ea6e   11 seconds ago   917MB</pre><p>Run the Docker image locally by following the instructions on the printed messages.</p><pre>$ docker run --rm -p 3000:3000 rag_service:73ikq6ayikzzze5l</pre><h4>BentoCloud</h4><p>Compared with Docker, <a href="https://www.bentoml.com/">BentoCloud</a> provides a fully-managed infrastructure optimized for running inference with AI models. This AI inference platform offers more advanced features like autoscaling, GPU inference, built-in observability, and model orchestration, which will be covered in the subsequent blog posts in this series.</p><p><a href="https://l.bentoml.com/sign-up-from-blog-serving-a-llamaindex-rag-app-as-rest-apis">Sign up for BentoCloud</a> first, then <a href="https://docs.bentoml.com/en/latest/bentocloud/how-tos/manage-access-token.html">log in to it</a> via the BentoML CLI.</p><pre>bentoml cloud login \<br>    --api-token &#39;your-api-token&#39; \<br>    --endpoint &#39;your-bentocloud-endpoint-url&#39;</pre><p>Run bentoml deploy in the project directory (where bentofile.yaml exists) to deploy the LlamaIndex RAG app.</p><pre>bentoml deploy .</pre><p>Once it is up and running, use the ingest_text endpoint to inject a text file and then send a query to the query endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RxqwZ7Z2qPjThKSD.gif" /></figure><h3>Conclusion</h3><p>With BentoML, you can easily serve a LlamaIndex RAG app as a RESTful API server. The entire process only takes two steps: 1) Structure your RAG code into a stateful class; 2) Add type hints and BentoML decorators for generating REST APIs for serving.</p><p>With your RAG service as a REST API, you can deploy it with Docker or BentoCloud for production, and integrate other systems, such as web applications, with your RAG code over APIs. Note that this example uses a local file system for storage, which may limit horizontal scalability. For production, we recommend using BentoCloud along with hosted vector database services for enhanced scalability and performance.</p><p>While OpenAI models offer powerful capabilities, some use cases may require more custom solutions to meet specific needs for data privacy and security, cost, latency and reliability. In the next blog post, we will explain how to replace them with open-source embedding and language models to build private RAG.</p><h3>More on BentoML and LlamaIndex</h3><p>Check out the following resources to learn more:</p><ul><li>[Blog] <a href="https://www.bentoml.com/blog/building-rag-with-open-source-and-custom-ai-models">Building RAG with Open-Source and Custom AI Models</a></li><li>[Blog] <a href="https://www.bentoml.com/blog/scaling-ai-model-deployment">Scaling AI Models Like You Mean It</a></li><li>[Blog] <a href="https://www.bentoml.com/blog/deploying-a-large-language-model-with-bentoml-and-vllm">Deploying A Large Language Model with BentoML and vLLM</a></li><li>[Doc] <a href="https://docs.llamaindex.ai/en/stable/getting_started/starter_example/">LlamaIndex Starter Tutorial (OpenAI)</a></li><li>[Doc] <a href="https://docs.llamaindex.ai/en/stable/understanding/indexing/indexing/">LlamaIndex Indexing</a></li><li>[Doc] <a href="https://docs.bentoml.org/en/latest/guides/services.html">BentoML Services</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b2cdb93e925" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building RAG with Open-Source and Custom AI Models]]></title>
            <link>https://medium.com/bentoml/building-rag-with-open-source-and-custom-ai-models-9bae28546053?source=rss-45268e99b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bae28546053</guid>
            <category><![CDATA[bentocloud]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[bentoml]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Sherlock Xu]]></dc:creator>
            <pubDate>Mon, 06 May 2024 08:19:06 GMT</pubDate>
            <atom:updated>2024-05-06T08:19:06.939Z</atom:updated>
            <content:encoded><![CDATA[<p>Retrieval-Augmented Generation (RAG) is a widely used application pattern for Large Language Models (LLMs). It uses information retrieval systems to give LLMs extra context, which aids in answering user queries not covered in the LLM’s training data and helps to prevent hallucinations. In this blog post, we draw from our experience working with <a href="http://www.bentoml.com/">BentoML</a> customers to discuss:</p><ul><li>Common challenges in making a RAG system ready for production</li><li>How to use open-source or custom fine-tuned models to enhance RAG performance</li><li>How to build scalable AI systems comprising multiple models and components</li></ul><p>By the end of this post, you’ll learn the basics of how open-source and custom AI/ML models can be applied in building and improving RAG applications.</p><p><strong>Note</strong>: This blog post is based on <a href="https://www.youtube.com/watch?v=2tm0b8_TVr8">this video</a>, with additional details.</p><h3>Simple RAG system</h3><p>A simple RAG system consists of 5 stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/0*KGtYwy6qQ4ByXdZu.png" /></figure><ul><li><strong>Chunking</strong>: RAG begins with turning your structured or unstructured dataset into text documents, and breaking down text into small pieces (chunks).</li><li><strong>Embed documents</strong>: A text embedding model steps in, turning each chunk into vectors representing their semantic meaning.</li><li><strong>VectorDB</strong>: These embeddings are then stored in a vector database, serving as the foundation for data retrieval.</li><li><strong>Retrieval</strong>: Upon receiving a user query, the vector database helps retrieve chunks relevant to the user’s request.</li><li><strong>Response Generation</strong>: With context, an LLM synthesizes these pieces to generate a coherent and informative response.</li></ul><p>Implementing a simple RAG system with a text embedding model and an LLM might initially only need a few lines of Python code. However, dealing with real-world datasets and improving performance for the system require more than that.</p><h3>Challenges in production RAG</h3><p>Building a RAG for production is no easy feat. Here are some of the common challenges:</p><h3>Retrieval performance</h3><ul><li><strong>Recall</strong>: Not all chunks that are relevant to the user query are retrieved.</li><li><strong>Precision</strong>: Not all chunks retrieved are relevant to the user query.</li><li><strong>Data ingestion</strong>: Complex documents, semi-structured and unstructured data.</li></ul><h3>Response synthesis</h3><ul><li><strong>Safeguarding</strong>: Is the user query toxic or offensive and how to handle it.</li><li><strong>Tool use</strong>: Use tools such as browsers or search engines to assist the response generation.</li><li><strong>Context accuracy</strong>: Retrieved chunks lacking necessary context or containing misaligned context.</li></ul><h3>Response evaluation</h3><ul><li><strong>Synthetic dataset for evaluation</strong>: LLMs can be used to create evaluation datasets for measuring the RAG system’s responses.</li><li><strong>LLMs as evaluators</strong>: LLMs also serve as evaluators themselves.</li></ul><h3>Improving RAG pipeline with custom AI models</h3><p>To build a robust RAG system, you need to take into account a set of building blocks or baseline components. These elements or decisions form the foundation upon which your RAG system’s performance is built.</p><h3>Text embedding model</h3><p>Common models like text-embedding-ada-002, while popular, may not be the best performers across all languages and domains. Their one-size-fits-all approach often falls short when you have nuanced requirements for specialized fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P0uRGg8miQl87a7T.png" /><figcaption>Source: Hugging Face <a href="https://huggingface.co/spaces/mteb/leaderboard">Massive Text Embedding Benchmark (MTEB) Leaderboard</a></figcaption></figure><p>On this note, fine-tuning an embedding model on a domain-specific dataset often enhances the retrieval accuracy. This is due to the improvement of embedding representations for the specific context during the fine-tuning process. For instance, while a general embedding model might associate the word “Bento” closely with “Food” or “Japan”, a model fine-tuned for AI inference would more likely connect it with terms like “Model Serving”, “Open Source Framework”, and “AI Inference Platform”.</p><h3>Large language model</h3><p>While GPT-4 leads the pack in performance, not all applications require such firepower. Sometimes, a more modest and well-optimized model can deliver the speed and cost-effectiveness needed, especially when provided with the right context. In particular, consider the following questions when choosing the LLM for your RAG:</p><ul><li><strong>Security and privacy</strong>: What level of control do you need over your data?</li><li><strong>Latency requirement</strong>: What is your TTFT (Time to first token) and TPOT (Time per output token) requirement? Is it serving real-time chat applications or offline data processing jobs?</li><li><strong>Reliability</strong>: For mission-critical applications, dedicated deployment that you control, often provides more reliable response time and generation quality.</li><li><strong>Capabilities</strong>: What tasks do you need your LLM to perform? For simple tasks, can it be replaced by a smaller specialized models?</li><li><strong>Domain knowledge</strong>: Does an LLM trained on general web content understand your specific domain knowledge?</li></ul><p>These questions are important no matter you are self-hosting open-source models or using commercial model endpoints. The right model should align with your data policies, budget plan, and the specific demands of your RAG application.</p><h3>Context-aware chunking</h3><p>Most simple RAG systems rely on fixed-size chunking, dividing documents into equal segments with some overlap to ensure continuity. This method, while straightforward, can sometimes strip away the rich context embedded in the data.</p><p>By contrast, context-aware chunking breaks down text data into more meaningful pieces, considering the actual content and its structure. Instead of splitting text at fixed intervals (like word count), it identifies logical breaks in the text using NLP techniques. These breaks can occur at the end of sentences, paragraphs, or when topics shift. This ensures each chunk captures a complete thought or idea, and makes it possible to add additional metadata to each chunk, for implementing metadata filtering or Small-to-Big retrieval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mJ9uBIhr4a9ppqZm.jpg" /></figure><p>As your RAG system can understand the overall flow and ideas within a document with context-aware chunking, it is capable of creating chunks that capture not just isolated sentences but also the broader context they belong to.</p><h3>Parsing complex documents</h3><p>The real world throws complex documents at us — product reviews, emails, recipes, and websites that not only contain textual content but are also enriched with structure, images, charts, and tables.</p><p>Traditional Optical Character Recognition (OCR) tools such as EasyOCR and Tesseract are proficient in transcribing text but often fall short when it comes to understanding the layout and contextual significance of the elements within a document.</p><p>For those grappling with the complexities of modern documents, consider integrating the following models and tools into your RAG systems:</p><ul><li><strong>Layout analysis: LayoutLM (and v2, v3)</strong> have been pivotal in advancing document layout analysis. <a href="https://arxiv.org/abs/2204.08387">LayoutLMv3</a>, in particular, integrates text and layout with image processing without relying on conventional CNNs, streamlining the architecture and leveraging masked language and image modeling, making it highly effective in understanding both text-centric and image-centric tasks.</li><li><strong>Table detection and extraction: </strong><a href="https://github.com/microsoft/table-transformer"><strong>Table Transformer (TATR)</strong></a> is specifically designed for detecting, extracting, and recognizing the structure of tables within documents. It operates similarly to object detection models, using a DETR-like architecture to achieve high precision in both table detection and functional analysis of table contents.</li><li><strong>Document question-answering systems:</strong> Building a Document Visual Question Answering (DocVQA) system often requires multiple models, such as models for layout analysis, OCR, entity extraction, and finally, models trained to answer queries based on the document’s content and structure. Tools like <a href="https://arxiv.org/abs/2111.15664">Donut</a> and the latest versions of LayoutLMv3 can be helpful in developing robust DocVQA systems.</li><li><strong>Fine-tuning:</strong> Existing open-source models are great places to start but with additional fine-tuning on your specific documents, handling its unique content or structure, can often lead to greater performance.</li></ul><h3>Metadata filtering</h3><p>Incorporating these models into your RAG systems, especially when combined with NLP techniques, allows for the extraction of rich metadata from documents. This includes elements like the sentiment expressed in text, the structure or summarization of a document, or the data encapsulated in a table. Most modern vector databases supports storing metadata alongside text embeddings, as well as using metadata filtering during retrieval, which can significantly enhance the retrieval accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wpyXzoUeouATAQzq.png" /></figure><h3>Reranking models</h3><p>While embedding models are a powerful tool for initial retrieval in RAG systems, they can sometimes return a large number of documents that might be generally relevant, but not necessarily the most precise answers to a user’s query. This is where <strong>reranking models</strong> come into play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wW_RB11F13BZRjX5.png" /><figcaption>Image source: <a href="https://www.pinecone.io/learn/series/rag/rerankers/">Rerankers and Two-Stage Retrieval</a></figcaption></figure><p>Reranking models introduce a two-step retrieval process that significantly improves precision:</p><ol><li><strong>Initial retrieval:</strong> An embedding model acts as a first filter, scanning the entire database and identifying a pool of potentially relevant documents. This initial retrieval is fast and efficient.</li><li><strong>Reranking:</strong> The reranking model then takes over, examining the shortlisted documents from the first stage. It analyzes each document’s content in more detail, considering its specific relevance to the user’s query. Based on this analysis, the reranking model reorders the documents, placing the most relevant ones at the top (sometimes at both ends of the context window for maximum relevance).</li></ol><p>While reranking provides superior precision, it adds an extra step to the retrieval process. Many may think this can increase latency. However, reranking also means you don’t need to send all retrieved chunks to the LLM, leading to faster generation time.</p><p>For more information, see this article <a href="https://www.pinecone.io/learn/series/rag/rerankers/">Rerankers and Two-Stage Retrieval</a>.</p><h3>Cross-modal retrieval</h3><p>While traditional RAG systems primarily focus on text data, <a href="https://arxiv.org/abs/2305.05665">research</a> like <a href="https://arxiv.org/abs/2305.05665">ImageBind: One Embedding Space To Bind Them All</a> is opening doors to a more versatile approach: Cross-modal retrieval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mc2jAU955fpYREk6.jpg" /><figcaption>Image source: <a href="https://arxiv.org/abs/2305.05665">ImageBind: One Embedding Space To Bind Them All</a></figcaption></figure><p>Cross-modal retrieval transcends traditional text-based limitations, supporting interplay between different types of data, such as audio and visual content. For example, when a RAG system incorporates models like <a href="https://arxiv.org/abs/2201.12086">BLIP</a> for visual reasoning, it’s able to understand the context within images, improving the textual data pipeline with visual insights.</p><p>While still in its early stages, multi-modal retrieval holds great potential what RAG systems can achieve.</p><h3>Recap: AI models in RAG systems</h3><p>As we improve our RAG system for production, the complexity increases accordingly. Ultimately, we may find ourselves orchestrating a group of AI models, each playing its part in the workflow of data processing and response generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tvlo5SWj0-mBpIFY.png" /></figure><p>As we address these complexities, we also need to pay attention to the infrastructure for deploying AI models. In the next part of this blog post, we’ll explore these infrastructure challenges and introduce how BentoML is contributing to this space.</p><h3>Scaling RAG services with multiple custom AI models</h3><h4>Serving embedding models</h4><p>One of the most frequent challenges is efficiently serving the embedding model. BentoML can help improve its performance in the following ways:</p><ul><li><strong>Asynchronous non-blocking invocation</strong>: BentoML allows you to <a href="https://docs.bentoml.com/en/latest/guides/services.html#convert-synchronous-to-asynchronous">convert synchronous inference methods of a model to asynchronous calls</a>, providing non-blocking implementation and improving performance in IO-bound operations.</li><li><strong>Shared model replica across multiple API workers</strong>: BentoML supports running shared model replicas across multiple <a href="https://docs.bentoml.com/en/latest/guides/workers.html">API workers</a>, each assigned with a specific GPU. This can maximize parallel processing, increase throughput, and reduce overall inference time.</li><li><strong>Adaptive batching</strong>: Within a BentoML Service, there is a dispatcher that manages how batches should be optimized by dynamically adjusting batch sizes and wait time to suit the current load. This mechanism is called <a href="https://docs.bentoml.com/en/latest/guides/adaptive-batching.html">adaptive batching</a> in BentoML. In the context of text embedding models, we often see performance improvements up to 3x in latency and 2x in throughput comparing to non-batching implementations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6peqtKQ7gYekmYXX.png" /></figure><p>For more information, see this <a href="https://github.com/bentoml/BentoSentenceTransformers">BentoML example project to deploy an embedding model</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KwlbHgOb-kHtmtVd.png" /></figure><h4>Self-hosting LLMs</h4><p>Many developers may start with pulling a model from Hugging Face and run it with frameworks like PyTorch or Transformers. This is fine for development and exploration, but performs poorly when serving high throughput workloads in production.</p><p>There are a variety of open-source tools like vLLM, <a href="https://github.com/bentoml/OpenLLM">OpenLLM</a>, mlc-llm, and TensorRT-LLM available for self-hosting LLMs. Consider the following when choosing such tools:</p><ul><li><strong>Inference best practices</strong>: Does the tool support optimized LLM inference? Techniques like continuous batching, Paged Attention, Flash Attention, and automatic prefix caching need to be implemented for efficient performance.</li><li><strong>Customizations</strong>: LLM behavior needs customized control like advanced stop conditioning (when a model should cease generating further content), specific output formats (ensuring the results adhere to a specific structure or standard), or input validation (using a classification model to detect). If you need such customization, consider using <a href="https://github.com/bentoml/BentoVLLM">BentoML + vLLM</a>.</li></ul><p>In addition to the LLM inference server, the infrastructure required for scaling LLM workloads also comes with unique challenges. For example:</p><ul><li><strong>GPU Scaling</strong>: Unlike traditional workloads, GPU utilization metrics can be deceptive for LLMs. Even if the metrics suggest full capacity, there might still be room for more requests and more throughput. This is why solutions like BentoCloud offers <a href="https://docs.bentoml.com/en/latest/bentocloud/how-tos/autoscaling.html">concurrency-based autoscaling</a>. Such an approach learns the semantic meanings of different requests, using <a href="https://docs.bentoml.com/en/latest/guides/adaptive-batching.html">dynamic batching</a> and wise resource management strategies to scale effectively.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TKaFF5tp_w7zkjcN.png" /></figure><ul><li><strong>Cold start and fast scaling</strong> <strong>with large container image and model files</strong>: Downloading large images and models from remote storage and loading models into GPU memory is a time-consuming process, <strong>breaking most existing cloud infrastructure’s assumptions about the workload.</strong> Specialized infrastructure, like BentoCloud, helps accelerate this process via <strong>lazy image pulling,</strong> <strong>streaming model loading</strong> and <strong>in-cluster caching</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I2X4AhVwl7p2uwJv.png" /></figure><p>For details, refer to <a href="https://www.bentoml.com/blog/scaling-ai-model-deployment">Scaling AI Model Deployment</a>.</p><h3>Model composition</h3><p><a href="https://docs.bentoml.com/en/latest/guides/model-composition.html">Model composition</a> is a strategy that combines multiple models to solve a complex problem that cannot be easily addressed by a single model. Before we talk about how BentoML can help you compose multiple models for RAG, let’s take a look at other two typical scenarios used in RAG systems.</p><h4>Document Processing Pipeline</h4><p>A document processing pipeline consists of multiple AI/ML models, each specializing in a stage of the data conversion process. In addition to OCR that extract text from images, it can extend to layout analysis, table extraction and image understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uDUsTY5YRoMw4Jne.png" /></figure><p>The models used in this process might have different resource requirements, some requiring GPUs for model inference and others, more lightweight, running efficiently on CPUs. Such a setup naturally fits into a distributed system of micro-services, each service serving a different AI model or function. This architectural choice can drastically improve resource utilization and reduce cost.</p><p>BentoML facilitates this process by allowing users to easily implement a distributed inference graph, where each stage can be a separate BentoML Service wrapping the capability of the corresponding model. In production, they can be deployed and scaled separately (more details can be found below).</p><h4>Using small language models</h4><p>In some cases, “small” models can be an ideal choice for their efficiency, particularly for simpler, more direct tasks like summarization, classification, and translation. Here’s how and why they fit into a multi-model system:</p><ul><li><strong>Rapid response:</strong> For example, when a user query is submitted, a small model like BERT can swiftly determine if the request is inappropriate or toxic. If so, it can reject the query directly, conserving resources by avoiding the follow-up steps.</li><li><strong>Routing</strong>: These nimble models can act as request routers. Fine-tuned BERT-like model needs no more than 10 milliseconds to identify which tools or data sources are needed for a given request. By contrast, an LLM may need a few seconds or more to complete.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wKrR-uwarB0zaC0-.png" /></figure><h4>Uniting separate RAG components</h4><p>Running a RAG system with a large number of custom AI models on a single GPU is highly inefficient, if not impossible. Although each model could be deployed and hosted separately, this approach makes it challenging to iterate and enhance the system as a whole.</p><p>BentoML is optimized for building such serving systems, streamlining both the workflow from development to deployment and the serving architecture itself. Developers can encapsulate the entire RAG logic within a single Python application, referencing each component (like OCR, reranker, text embedding, and large language models) as a straightforward Python function call. The framework eliminates the need to build and manage distributed services, optimizing resource efficiency and scalability for each component. BentoML also manages the entire pipeline, packaging the necessary code and models into a single versioned unit (a “Bento”). This consistency across different application lifecycle stages drastically simplifies the deployment and evaluation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*URbw2S8UasxzDYui.png" /></figure><blockquote>Note: In the next series of blog posts, we will dive into more details on how developers can leverage BentoML for model composition and serving RAG systems at scale. Stay tuned!</blockquote><p>To summarize, here is how BentoML can help you build RAG systems:</p><ul><li>Define the entire RAG components within one Python file</li><li>Compile them to one versioned unit for evaluation and deployment</li><li>Adopt baked-in model serving and inference best practices like adaptive batching</li><li>Assign each model inference components to different GPU shapes and scale them independently for maximum resource efficiency</li><li>Monitor production performance in BentoCloud, which provides comprehensive observability like tracing and logging</li></ul><p>For more information, refer to <a href="https://github.com/bentoml/rag-tutorials">our RAG tutorials</a>.</p><h3>Conclusion</h3><p>Modern RAG systems often requires a large number of open-source and custom fine-tuned AI models for achieving the optimal performance. As we improve RAG systems with all these additional AI models, the complexity grows quickly, which not only slows down your development iterations, but also comes with a high cost in deploying and maintaining such a system in production.</p><p>BentoML is designed for building and serving compound AI systems with multiple models and components easily. It comes in handy in the orchestration of complex RAG systems, ensuring seamless scaling in the cloud.</p><h3>More on BentoML</h3><p>To learn more about BentoML, check out the following resources:</p><ul><li>[Blog] <a href="https://www.bentoml.com/blog/introducing-bentoml-1-2">Introducing BentoML 1.2</a></li><li>[Blog] <a href="https://www.bentoml.com/blog/deploying-solar-with-bentoml">Deploying Solar with BentoML</a></li><li>[Blog] <a href="https://www.bentoml.com/blog/scaling-ai-model-deployment">Scaling AI Models Like You Mean It</a></li><li>If you are interested in our AI inference platform BentoCloud, <a href="https://l.bentoml.com/sign-up-from-blog-building-rag-with-open-source-and-custom-ai-models">sign up</a> now and get $10 in free credits!</li><li>Join the <a href="https://l.bentoml.com/join-slack-from-blog-building-rag-with-open-source-and-custom-ai-models">BentoML Slack community</a> to get help and <a href="https://l.bentoml.com/contact-us-from-blog-building-rag-with-open-source-and-custom-ai-models">contact us</a> to schedule a call with our expert!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bae28546053" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentoml/building-rag-with-open-source-and-custom-ai-models-9bae28546053">Building RAG with Open-Source and Custom AI Models</a> was originally published in <a href="https://medium.com/bentoml">BentoML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Open-Source Image Generation Models]]></title>
            <link>https://medium.com/bentoml/a-guide-to-open-source-image-generation-models-e64db6626bfe?source=rss-45268e99b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e64db6626bfe</guid>
            <category><![CDATA[text-to-image-generation]]></category>
            <category><![CDATA[bentocloud]]></category>
            <category><![CDATA[bentoml]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <dc:creator><![CDATA[Sherlock Xu]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 04:53:11 GMT</pubDate>
            <atom:updated>2024-05-02T13:18:01.295Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/bentoml/navigating-the-world-of-large-language-models-8f2299c86acc">In my previous article</a>, I talked about the world of Large Language Models (LLMs), introducing some of the most advanced open-source text generation models over the past year. However, LLMs are only one of the important players in today’s rapidly evolving AI world. Equally transformative and innovative are the models designed for visual creation, like text-to-image, image-to-image, and image-to-video models. They have opened up new opportunities for creative expression and visual communication, enabling us to generate beautiful visuals, change backgrounds, inpaint missing parts, replicate compositions, and even turn simple scribbles into professional images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpWfiw2iyEhU0v5-H3THtA.jpeg" /></figure><p>One of the most mentioned names in this field is Stable Diffusion, which comes with a series of open-source visual generation models, like Stable Diffusion 1.4, 2.0 and XL, mostly developed by Stability AI. However, in the expansive universe of AI-driven image generation, they represent merely a part of it and things can get really complicated as you begin to choose the right model for serving and deployment. A quick search on Hugging Face <a href="https://huggingface.co/models?pipeline_tag=text-to-image">gives over 18,000 text-to-image models alone</a>.</p><p>In this blog post, we will provide a featured list of open-source models that stand out for their ability in generating creative visuals. Just like the previous blog post, we will also answer frequently asked questions to help you navigate this exciting yet complex domain, providing insights into using these models in production.</p><h3>Stable Diffusion</h3><p><a href="https://huggingface.co/models?other=stable-diffusion">Stable Diffusion (SD)</a> has quickly become a household name in generative AI since its launch in 2022. It is capable of generating photorealistic images from both text and image prompts. You might often hear people use the term “diffusion models” together with Stable Diffusion, which is the base AI technology that powers Stable Diffusion. Simply put, diffusion models generate images by starting with a pattern of random noise and gradually shaping it into a coherent image through a process that reversibly adds and removes noise. This process is computationally intensive but has been optimized in Stable Diffusion with latent space technology.</p><p>Latent space is like a compact, simplified map of all the possible images that the model can create. Instead of dealing with every tiny detail of an image (which takes a lot of computing power), the model uses this map to find and create new images more efficiently. It’s a bit like sketching out the main ideas of a picture before filling in all the details.</p><p>In addition to static images, Stable Diffusion can also produce videos and animations, making it a comprehensive tool for a variety of creative tasks.</p><p>Why should you use Stable Diffusion:</p><ul><li><strong>Multiple variants</strong>: Stable Diffusion comes with a variety of popular base models, such as Stable Diffusion 1.4, 1.5, 2.0, and 2.1, Stable Diffusion XL, Stable Diffusion XL Turbo, and Stable Video Diffusion. <a href="https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0#evaluation">According to this evaluation graph</a>, the SDXL base model performs significantly better than the previous variants. Nevertheless, I think it is not 100% easy to say which model generates better images than others, as the results can impacted by various factors, like prompt, inference steps and LoRA weights. Some models even have more LoRAs available, which is an important factor when choosing the right model. For beginners, I recommend you start with SD 1.5 or SDXL 1.0. They’re user-friendly and rich in features, perfect for exploring without getting into the technical details.</li><li><strong>Customization and fine-tuning</strong>: Stable Diffusion base models can be fine-tuned with as little as five images for generating visuals in specific styles or of particular subjects, enhancing the relevance and uniqueness of generated images. One of my favorites is <a href="https://huggingface.co/ByteDance/SDXL-Lightning">SDXL-Lightning</a>, built upon Stable Diffusion XL; it is known for its lightning-fast capability to generate high-quality images in just a few steps (1, 2, 4, and 8 steps).</li><li><strong>Controllable</strong>: Stable Diffusion provides you with extensive control over the image generation process. For example, you can adjust the number of steps the model takes during the diffusion process, set the image size, specify the seed for reproducibility, and tweak the guidance scale to influence the adherence to the input prompt.</li><li><strong>Future potential</strong>: There’s vast potential for integration with animation and video AI systems, promising even more expansive creative possibilities.</li></ul><p>Points to be cautious about:</p><ul><li><strong>Distortion</strong>: Stable Diffusion can sometimes inaccurately render complex details, particularly faces, hands, and legs. These mistakes might not be immediately noticeable. To improve the generated images, you can try to add a negative prompt or use specific fine-tuned versions.</li><li><strong>Text generation</strong>: Stable Diffusion has difficulties in understanding and creating text within images, which is not uncommon for image generation models.</li><li><strong>Legal concerns</strong>: Using AI-generated art could pose long-term legal challenges, especially if the training data wasn’t thoroughly vetted for copyright issues. This isn’t specific to Stable Diffusion and I will talk more about it in an FAQ later.</li><li><strong>Similarity risks</strong>: Given the data Stable Diffusion was trained on, there’s a possibility of generating similar or duplicate results when artists and creators use similar keywords or prompts.</li></ul><p><strong>Note</strong>: <a href="https://stability.ai/news/stable-diffusion-3">Stable Diffusion 3</a> was just released last month but it is only for early preview.</p><h3>DeepFloyd IF</h3><p><a href="https://github.com/deep-floyd/IF">DeepFloyd IF</a> is a text-to-image generation model developed by Stability AI and the DeepFloyd research lab. It stands out for its ability to produce images with remarkable photorealism and nuanced language understanding.</p><p>DeepFloyd IF’s architecture is particularly noteworthy for its approach to diffusion in pixel space. Specifically, it contains a text encoder and three cascaded pixel diffusion modules. Each module plays a unique role in the process: Stage 1 is responsible for the creation of a base 64x64 px image, which is then progressively upscaled to 1024x1024 px across Stage 2 and Stage 3. This distinguishes itself from latent diffusion models like Stable Diffusion. This pixel-level processing allows DeepFloyd IF to directly manipulate images for generating or enhancing visuals without the need for translating into and from a compressed latent representation.</p><p>Why should you use DeepFloyd IF:</p><ul><li><strong>Text understanding</strong>: DeepFloyd IF integrates a large language model T5-XXL-1.1 for deep text prompt understanding, enabling it to create images that closely match input descriptions.</li><li><strong>Text rendering</strong>: DeepFloyd IF showcases tangible progress in rendering text with better coherence than previous models in the Stable Diffusion series and other text-to-image models. While it has its flaws, DeepFloyd IF marks a significant step forward in the evolution of image generation models in text rendering.</li><li><strong>High photorealism:</strong> DeepFloyd IF <a href="https://stability.ai/news/deepfloyd-if-text-to-image-model">achieves impressive zero-shot FID scores</a> (6.66), which means it is able to create high-quality, photorealistic images. The FID score is used to evaluate the quality of images generated by text-to-image models, and lower scores typically mean better quality.</li></ul><p>Points to be cautious about:</p><ul><li><strong>Content sensitivity</strong>: DeepFloyd IF was trained on a subset of the LAION-5B dataset, known for its wide-ranging content, including adult, violent, and sexual themes. Efforts have been made to mitigate the model’s exposure to such content, but you should remain cautious and review output if necessary.</li><li><strong>Bias and cultural representation</strong>: The model’s training on LAION-2B(en), a dataset with English-centric images and text, introduces a bias towards white and Western cultures, often treating them as defaults. This bias affects the diversity and cultural representation in the model’s output.</li><li><strong>Hardware requirements</strong>: You need a GPU with at least 24GB vRAM for running all its variants, making it resource-intensive.</li></ul><h3>ControlNet</h3><p><a href="https://arxiv.org/abs/2302.05543">ControlNet</a> can be used to enhance the capabilities of diffusion models like Stable Diffusion, allowing for more precise control over image generation. It operates by dividing neural network blocks into “locked” and “trainable” copies, where the trainable copy learns specific conditions you set, and the locked one preserves the integrity of the original model. This structure allows you to train the model with small datasets without compromising its performance, making it ideal for personal or small-scale device use.</p><p>Why should you use ControlNet:</p><ul><li><strong>Enhanced control over image generation</strong>: ControlNet introduces a higher degree of control by allowing additional conditions, such as edge detection or depth maps, to steer the final image output. This makes ControlNet a good choice when you want to clone image compositions, dictate specific human poses, or produce similar images.</li><li><strong>Efficient and flexible</strong>: The model architecture ensures minimal additional GPU memory requirements, making it suitable even for devices with limited resources.</li></ul><p>Points to be cautious about:</p><ul><li><strong>Dependency on Stable Diffusion</strong>: ControlNet relies on Stable Diffusion to function. This dependency could affect its usage in environments where Stable Diffusion might not be the preferred choice for image generation. In addition, the limitations of Stable Diffusion mentioned above could also impact the generated images, like distortion and legal concerns.</li></ul><h3>Animagine XL</h3><p>Text-to-image AI models hold significant potential for the animation industry. Artists can quickly generate concept art by providing simple descriptions, allowing for rapid exploration of visual styles and themes. In this area, Animagine XL is one of the important players leading the innovation. It represents a series of open-source anime text-to-image generation models. Built upon Stable Diffusion XL, its latest release <a href="https://huggingface.co/cagliostrolab/animagine-xl-3.1">Animagine XL 3.1</a> adopts tag ordering for prompts, which means the sequence of prompts will significantly impact the output. To ensure the generated results are aligned with your intention, <a href="https://huggingface.co/cagliostrolab/animagine-xl-3.1#tag-ordering">you may need to follow certain template</a> as the model was trained this way.</p><p>Why should you use Animagine XL:</p><ul><li><strong>Tailored anime generation</strong>: Designed specifically for anime-style image creation, it offers superior quality in this genre. If you are looking for a model to create this type of images, Animagine XL can be the go-to choice.</li><li><strong>Expanded knowledge base</strong>: Animagine XL integrates a large number of anime characters, enhancing the model’s familiarity across a broader range of anime styles and themes.</li></ul><p>Points to be cautious about:</p><ul><li><strong>Niche focus</strong>: Animagine XL is primarily designed for anime-style images, which might limit its application for broader image generation needs.</li><li><strong>Learning curve</strong>: Mastering tag ordering and prompt interpretation for optimal results may require familiarity with anime genres and styles.</li></ul><h3>Stable Video Diffusion</h3><p>Stable Video Diffusion (SVD) is a video generation model from Stability AI, aiming to provide high-quality videos from still images. As mentioned above, this model is a part of Stability AI’s suite of AI tools and represents their first foray into open video model development.</p><p>Stable Video Diffusion is capable of generating 14 and 25 frames at customizable frame rates between 3 and 30 frames per second. <a href="https://huggingface.co/stabilityai/stable-video-diffusion-img2vid-xt#evaluation">According to this evaluation graph</a>, SVD gained more human voters in terms of video quality over <a href="https://research.runwayml.com/gen2">GEN-2</a> and <a href="https://www.pika.art/">PikaLabs</a>.</p><p>In fact, Stability AI is still working on it to improve both its safety and quality. Stability AI emphasized that “<a href="https://stability.ai/news/stable-video-diffusion-open-ai-video-model">this model is not intended for real-world or commercial applications at this stage and it is exclusively for research</a>”. That said, it is one of the few open-source video generation models available in this industry. If you just want to play around with it, pay attention to the following:</p><ul><li><strong>Short video length</strong>: The model can only generate short video sequences, with a maximum length of around 4 seconds, limiting the scope for longer narrative or detailed exploration.</li><li><strong>Motion limitations</strong>: Some generated videos may lack dynamic motion, resulting in static scenes or very slow camera movements that might not meet the expectations in certain use cases.</li><li><strong>Distortion</strong>: Stable Video Diffusion may not accurately generate faces and people, often resulting in less detailed or incorrect representations, posing challenges for content focused on human subjects.</li></ul><p>Now let’s answer some of the frequently asked questions for open-source image generation models. Questions like “Why should I choose open-source models over commercial ones?” and “What should I consider when deploying models in production?” are already <a href="https://www.bentoml.com/blog/navigating-the-world-of-large-language-models">covered in my previous blog post</a>, so I do not list them here.</p><h3>What is LoRA? What can I do with it and Stable Diffusion?</h3><p>LoRA, or Low-Rank Adaptation, is an advanced technique designed for fine-tuning machine learning models, including generative models like Stable Diffusion. It works by using a small number of trainable parameters to fine-tune these models on specific tasks or to adapt them to new data. As it significantly reduces the number of parameters that need to be trained, it does not require extensive computational resources.</p><p>With LoRA, you can enhance Stable Diffusion models by customizing generated content with specific themes and styles. If you don’t want to create LoRA weights yourself, check out the LoRA resources on <a href="https://civitai.com/search/models?sortBy=models_v8&amp;query=lora">Civitai</a>.</p><h3>How can I create high-quality images?</h3><p>Creating high-quality images with image generation models involves a blend of creativity, precision, and technical understanding. Some key strategies to improve your outcomes:</p><ul><li><strong>Be detailed and specific</strong>: Use detailed and specific descriptions in your prompt. The more specific you are about the scene, subject, mood, lighting, and style, the more accurately the model can generate your intended image. For example, instead of saying “a cat”, input something like “a fluffy calico cat lounging in the afternoon sun by a window with sheer curtains”.</li><li><strong>Layered prompts</strong>: Break down complex scenes into layered prompts. First, describe the setting, then the main subjects, followed by details like emotions or specific actions. This will help you guide the model understand your prompt.</li><li><strong>Reference artists or works</strong>: Including the names of artists or specific art pieces can help steer the style of the generated image. However, be mindful of copyright considerations and use this approach for inspiration rather than replication.</li></ul><h3>Should I worry about copyright issues when using image generation models?</h3><p>The short answer is YES.</p><p>Copyright concerns are a significant aspect to consider when using image generation models, including not just open-source models but commercial ones. There have been lawsuits against companies behind popular image generation models <a href="https://www.findlaw.com/legalblogs/federal-courts/judge-trims-copyright-lawsuit-against-ai-model-stable-diffusion/">like this one</a>.</p><p>Many models are trained on vast datasets that include copyrighted images. This raises questions about the legality of using these images as part of the training process.</p><p>Another thing is that determining the copyright ownership of AI-generated images can be complex. If you’re planning to use these images commercially, it’s important to consider who holds the copyright — the user who inputs the prompt, the creators of the AI model, or neither.</p><p>So, what can you do?</p><p>At this stage, the best suggestion I can give to someone using these models and the images they create is to stay informed. The legal landscape around AI-generated images is still evolving. Keep abreast of ongoing legal discussions and rulings related to AI and copyright law. Understanding your rights and the legal status of AI-generated images is crucial for using these tools ethically and legally.</p><h3>What is the difference between deploying LLMs and image generation models in production?</h3><p>Deploying LLMs and image generation models in production requires similar considerations on factors like scalability and observability, but they also have their unique challenges and requirements.</p><ul><li><strong>Resource requirements</strong>: Image generation models, especially high-resolution video or image models, typically demand more computational power and memory than LLMs due to the need to process and generate complex visual data. LLMs, while also resource-intensive, often have more predictable computational and memory usage patterns.</li><li><strong>Latency and throughput</strong>: Image generation tasks can have higher latency due to the processing involved in creating detailed visuals. Optimizing latency and throughput might require different strategies for image models compared to LLMs, such as adjusting model size or using specialized hardware accelerators (GPUs).</li><li><strong>Data sensitivity and privacy</strong>: Deploying both types of models in production needs wise data handling and privacy measures. However, image generation models may require additional considerations due to the potential for generating images that include copyrighted elements.</li><li><strong>User experience</strong>: For image generation models, I will recommend you provide users with guidance on creating effective prompts, which can enhance the quality of generated images. You may need to design the user interface by considering the model’s response time and output characteristics.</li></ul><h3>Final thoughts</h3><p>Just like LLMs, choosing the right model for image generation requires us to understand their strengths and limitations. Each model brings its unique capabilities to the table, supporting different real-world use cases. Currently, I believe the biggest challenge for image generation models is ethical and copyright concerns. As we embrace the potential of them to augment our creative process, it’s equally important to use these tools responsibly and respect copyright laws, privacy rights, and ethical guidelines.</p><h3>More on image generation models</h3><ul><li>If you are looking for a way to deploy diffusion models in production, feel free to <a href="https://docs.bentoml.com/en/latest/use-cases/diffusion-models/index.html">try these tutorials</a>.</li><li>Try <a href="https://l.bentoml.com/sign-up-from-blog-a-guide-to-open-source-image-generation-models">BentoCloud</a> and get $10 in free credits on signup! Experience a serverless platform tailored to simplify the building and management of your AI applications, ensuring both ease of use and scalability.</li><li>Join our <a href="https://l.bentoml.com/join-slack">Slack community</a> to get help and the latest information on BentoML!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e64db6626bfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentoml/a-guide-to-open-source-image-generation-models-e64db6626bfe">A Guide to Open-Source Image Generation Models</a> was originally published in <a href="https://medium.com/bentoml">BentoML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying A Large Language Model with BentoML and vLLM]]></title>
            <link>https://medium.com/bentoml/deploying-a-large-language-model-with-bentoml-and-vllm-180dcb5c6622?source=rss-45268e99b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/180dcb5c6622</guid>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[bentoml]]></category>
            <category><![CDATA[bentocloud]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Sherlock Xu]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 03:27:30 GMT</pubDate>
            <atom:updated>2025-07-25T06:29:18.446Z</atom:updated>
            <content:encoded><![CDATA[<p>Large language models (LLMs) promise to redefine our interaction with technology across various industries. Yet, the leap from the promise of LLMs to their practical application presents a significant hurdle. The challenge lies not just in developing and training them, but in serving and deploying them efficiently and cost-effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQnXEnlVgiPyI0u7pXC5ZA.jpeg" /></figure><p>In previous blog posts, we delved into using BentoCloud for deploying ML servers, showcasing its ability to offer serverless infrastructure tailored for optimal cost efficiency. Upon this foundation, we can integrate a new tool to enhance our BentoML Service for better LLM inference and serving: <a href="https://github.com/vllm-project/vllm">vLLM</a>.</p><p>In this blog post, let’s see how we can create an LLM server built with vLLM and BentoML, and deploy it in production with BentoCloud. By the end of this tutorial, you will have an interactive AI assistant as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_AEyCUCRf7D6ePVU.gif" /></figure><h3>What is vLLM?</h3><p>vLLM is a fast and easy-to-use open-source library for LLM inference and serving. Developed by the minds at UC Berkeley and deployed at <a href="https://chat.lmsys.org/">Chatbot Arena and Vicuna Demo</a>, vLLM is equipped with an arsenal of features. To name a few:</p><ul><li><strong>Dramatic performance boost</strong>: vLLM leverages PagedAttention to achieve up to 24x higher throughput than Hugging Face Transformers, making LLM serving faster and more efficient.</li><li><strong>Ease of use</strong>: Designed for straightforward integration, vLLM simplifies the deployment of LLMs with an easy-to-use interface.</li><li><strong>Cost-effective</strong>: Optimizes resource use, significantly lowering the computational cost and making LLM deployment accessible even for teams with limited compute resources.</li></ul><p>See this article <a href="https://blog.vllm.ai/2023/06/20/vllm.html">vLLM: Easy, Fast, and Cheap LLM Serving with PagedAttention</a> to learn more about vLLM.</p><h3>Setting up the environment</h3><p>As always, I suggest you set up a virtual environment for your project to keep your dependencies organized:</p><pre>python -m venv vllm-bentoml-env<br>source vllm-bentoml-env/bin/activate</pre><p>Then, clone the project’s repo and install all the required dependencies.</p><pre>git clone https://github.com/bentoml/BentoVLLM.git<br>cd BentoVLLM/mistral-7b-instruct<br>pip install -r requirements.txt &amp;&amp; pip install -f -U &quot;pydantic&gt;=2.0&quot;</pre><p>The stage is now set. Let’s get started!</p><h3>Defining a BentoML Service</h3><p>1. Create a BentoML Service file service.py (already available in the repo you cloned) and open it in your preferred text editor. We&#39;ll start by importing necessary modules:</p><pre>import uuid<br>from typing import AsyncGenerator<br>import bentoml<br>from annotated_types import Ge, Le<br>from typing_extensions import Annotated<br>from bentovllm_openai.utils import openai_endpoints</pre><p>These imports are for asynchronous operations, type checking, and the integration of BentoML and vLLM-specific functionalities. You will know more about them in the following sections.</p><p>2. Next, specify the model to use and set some ground rules for it. For this project, I will use mistralai/Mistral-7B-Instruct-v0.2, which is reported to have outperformed the Llama 2 13B model in all the benchmark tests. You can choose <a href="https://docs.vllm.ai/en/latest/models/supported_models.html">any other model supported by vLLM</a>.</p><p>Also, set the maximum token limit for the model’s responses and use a template for our prompts. This template is like a script for how we want our model to behave — polite, respectful, and safe:</p><pre>MODEL_ID = &quot;mistralai/Mistral-7B-Instruct-v0.2&quot;<br><br>MAX_TOKENS = 1024<br>PROMPT_TEMPLATE = &quot;&quot;&quot;&lt;s&gt;[INST]<br>You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.<br><br>If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don&#39;t know the answer to a question, please don&#39;t share false information.<br><br>{user_prompt} [/INST] &quot;&quot;&quot;</pre><p>3. Now we can begin to design the BentoML Service. Starting from BentoML 1.2, we use the @bentoml.service decorator to mark a Python class as a BentoML Service. <a href="https://docs.bentoml.org/en/latest/guides/configurations.html">Additional configurations</a> like timeout can be set to customize its runtime behavior. The resources field specifies the GPU requirements as we will deploy this Service on BentoCloud later; cloud instances will be provisioned based on it.</p><p>In addition, use the @openai_endpoints decorator from bentovllm_openai.utils (<a href="https://github.com/bentoml/BentoVLLM/tree/main/bentovllm_openai">available here</a>) to set up OpenAI-compatible endpoints. This is like giving the Service a universal adapter, allowing it to interact with various clients as if it were an OpenAI service itself.</p><pre>@openai_endpoints(served_model=MODEL_ID)<br>@bentoml.service(<br>    name=&quot;mistral-7b-instruct-service&quot;,<br>    traffic={<br>        &quot;timeout&quot;: 300,<br>    },<br>    resources={<br>        &quot;gpu&quot;: 1,<br>        &quot;gpu_type&quot;: &quot;nvidia-l4&quot;,<br>    },<br>)<br>class VLLM:</pre><p>4. Within the class, set an LLM engine by specifying the model and how many tokens it should generate. Read the <a href="https://docs.vllm.ai/en/latest/dev/engine/async_llm_engine.html">vLLM documentation</a> to learn more about the modules imported here.</p><pre>class VLLM:<br>    def __init__(self) -&gt; None:<br>        from vllm import AsyncEngineArgs, AsyncLLMEngine<br>        ENGINE_ARGS = AsyncEngineArgs(<br>            model=MODEL_ID,<br>            max_model_len=MAX_TOKENS<br>        )<br>        <br>        self.engine = AsyncLLMEngine.from_engine_args(ENGINE_ARGS)</pre><p>5. To interact with this Service, define an API method using @bentoml.api. It serves as the primary interface for processing input prompts and streaming back generated text.</p><pre>    @bentoml.api<br>    async def generate(<br>        self,<br>        # Accept a prompt with a default value; users can override this when calling the API<br>        prompt: str = &quot;Explain superconductors like I&#39;m five years old&quot;,<br>        # Enforce the generated response to be within a specified range using type annotations<br>        max_tokens: Annotated[int, Ge(128), Le(MAX_TOKENS)] = MAX_TOKENS,<br>    ) -&gt; AsyncGenerator[str, None]:<br>        from vllm import SamplingParams<br><br>        # Initialize the parameters for sampling responses from the LLM (maximum token in this case)<br>        SAMPLING_PARAM = SamplingParams(max_tokens=max_tokens)<br>        # Format the user&#39;s prompt with the predefined prompt template<br>        prompt = PROMPT_TEMPLATE.format(user_prompt=prompt)<br>        # Send the formatted prompt to the LLM engine asynchronously<br>        stream = await self.engine.add_request(uuid.uuid4().hex, prompt, SAMPLING_PARAM)<br> <br>        # Initialize a cursor to track the portion of the text already returned to the user<br>        cursor = 0<br>        async for request_output in stream:<br>            # Extract text from the first output<br>            text = request_output.outputs[0].text<br>            yield text[cursor:]<br>            cursor = len(text)</pre><p>That’s all the code! To run this project with bentoml serve, you need a NVIDIA GPU with at least 16G VRAM.</p><pre>bentoml serve .</pre><p>The server will be active at <a href="http://localhost:3000">http://localhost:3000</a>. You can communicate with it by using the curl command:</p><pre>curl -X &#39;POST&#39; \<br>  &#39;http://localhost:3000/generate&#39; \<br>  -H &#39;accept: text/event-stream&#39; \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>  &quot;prompt&quot;: &quot;Explain superconductors like I&#39;\&#39;&#39;m five years old&quot;,<br>  &quot;max_tokens&quot;: 1024<br>}&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/0*h0xbP1f-nk7b27DG.gif" /></figure><h3>Deploying the LLM to BentoCloud</h3><p>Deploying LLMs in production often requires significant computational resources, particularly GPUs, which may not be readily available on local machines. Therefore, you can use BentoCloud, a platform designed to simplify the deployment, management, and scaling of machine learning models, including those as resource-intensive as LLMs.</p><p>Before you can deploy this LLM to BentoCloud, you’ll need to:</p><ol><li><strong>Sign up</strong>: If you haven’t already, create an account on BentoCloud for free. Navigate to <a href="https://www.bentoml.com/">the BentoCloud website</a> and follow the sign-up process.</li><li><strong>Log in</strong>: Once your account is set up, <a href="https://docs.bentoml.com/en/latest/bentocloud/how-tos/manage-access-token.html">log in to BentoCloud</a>.</li></ol><p>With your BentoCloud account ready, navigate to your project’s directory where bentofile.yaml is stored (it is already available in the repo you cloned), then run:</p><pre>bentoml deploy .</pre><p>The deployment may take some time. When it is complete, you can interact with the LLM server on the BentoCloud console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QZzS8bvSroVBfqHo.gif" /></figure><h3>More on BentoML and vLLM</h3><p>To learn more about BentoML and vLLM, check out the following resources:</p><ul><li><a href="https://bentoml.com/llm/">LLM Inference Handbook</a></li><li>[Doc] <a href="https://docs.vllm.ai/en/latest/">vLLM documentation</a></li><li>[Doc] <a href="https://docs.bentoml.com/en/latest/use-cases/large-language-models/vllm.html">vLLM inference</a></li><li>[Blog] <a href="https://www.bentoml.com/blog/introducing-bentoml-1-2">Introducing BentoML 1.2</a></li><li>[Blog] <a href="https://www.bentoml.com/blog/deploying-a-text-to-speech-application-with-bentoml">Deploying A Text-To-Speech Application with BentoML</a></li><li>[Blog] <a href="https://dzone.com/articles/deploying-an-image-captioning-server-with-bentoml">Deploying An Image Captioning Server With BentoML</a></li><li>Try <a href="https://www.bentoml.com/">BentoCloud</a> and get $10 in free credits on signup! Experience a serverless platform tailored to simplify the building and management of your AI applications, ensuring both ease of use and scalability.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=180dcb5c6622" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentoml/deploying-a-large-language-model-with-bentoml-and-vllm-180dcb5c6622">Deploying A Large Language Model with BentoML and vLLM</a> was originally published in <a href="https://medium.com/bentoml">BentoML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the World of Large Language Models]]></title>
            <link>https://medium.com/bentoml/navigating-the-world-of-large-language-models-8f2299c86acc?source=rss-45268e99b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f2299c86acc</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[bentoml]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[bentocloud]]></category>
            <dc:creator><![CDATA[Sherlock Xu]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 03:09:28 GMT</pubDate>
            <atom:updated>2024-07-30T07:57:36.288Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the past year and a half, the AI world has been abuzz with the rapid release of large language models (LLMs), each boasting advancements that push the boundaries of what’s possible with generative AI. The pace at which new models are emerging is breathtaking. Recently, <a href="https://ai.meta.com/blog/meta-llama-3-1/">Meta AI introduced Llama 3.1</a>, with its 405B variant featuring better flexibility, control, and cutting-edge capabilities that can rival the best closed-source models. The very next day, <a href="https://mistral.ai/news/mistral-large-2407/">Mistral launched Mistral Large 2</a>, which competes on par with leading models like GPT-4o, Claude 3 Opus, and Llama 3 405B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0N_bbnBiBf_kOPstnZ-0w.jpeg" /></figure><p>These models, powered by an ever-increasing number of parameters and trained on colossal datasets, have improved our efficiency to generate text and write complex code. However, the sheer number of options available can feel both exciting and daunting. Making informed decisions about which to use — considering output quality, speed, and cost — becomes a problem.</p><p>The answer lies not just in the specifications sheets or benchmark scores but in a holistic understanding of what each model brings to the table. In this blog post, we curate a select list of open-source LLMs making waves over the past year. At the same time, we look to provide answers to some of the frequently asked questions.</p><h3>Llama 3.1</h3><p>Meta AI continues to push the boundaries of open-source AI with the release of Llama 3.1, available in 8, 70, and 405 billion parameters. It can be used across a broad spectrum of tasks, including chatbots and various natural language generation applications. Llama 3.1 is the latest addition to the Llama family, which boasts 300 million total downloads of all Llama versions to date.</p><p>Why should you use Llama 3.1:</p><ul><li><strong>Performance</strong>: Based on <a href="https://ai.meta.com/blog/meta-llama-3-1/">Meta AI’s benchmarks</a>, Llama 3.1 8B and 70B demonstrate superior comprehension, reasoning, and general intelligence capabilities compared to other open-source models like Gemma 2 9B IT and Mistral 7B &amp; 8*22B Instruct. Its largest version, 405B, is competitive with leading foundation models across a range of tasks, including GPT-4, GPT-4o, and Claude 3.5 Sonnet.</li><li><strong>Fine-tuning</strong>: With three different sizes, Llama 3.1 is an ideal foundation for a wide range of specialized applications. Users can fine-tune these models to meet the unique needs of specific tasks or industries. This also extends to previous versions of the Llama model family like Llama 2 and Llama 3 (<a href="https://huggingface.co/models?sort=trending&amp;search=Llama">over 45,000 search results for “Llama” in Hugging Face Model Hub</a>). These fine-tuned models not only save developers significant time and resources but also highlight Llama 3.1’s capacity for customization and improvement.</li><li><strong>Context window</strong>: Llama 3.1 significantly improves upon its predecessors with a large context window of 128k tokens. This enhancement makes it useful for enterprise use cases such as handling long chatbot conversations and processing large documents.</li><li><strong>Safety</strong>: Meta has implemented extensive safety measures for Llama 3.1, including Red Teaming exercises to identify potential risks. <a href="https://ai.meta.com/research/publications/the-llama-3-herd-of-models/">According to Meta’s research paper</a>, Llama 3 performs generally better at refusing inappropriate requests with lower false refusal rates and violation rates. However, they acknowledge that the numbers in the safety tests are not reproducible externally since safety benchmarks are internal to Meta, so they choose to anonymize the competitors in the test.</li></ul><p>Challenge with Llama 3.1:</p><ul><li><strong>Resource requirements</strong>: Given the large size, the 405 billion model requires substantial computational resources to run. Even with 4-bit quantization, the model remains around 200GB and may need multiple A100 GPUs to run effectively, which can be prohibitive for smaller organizations or individuals.</li></ul><p>As it was just released recently, more investigation is still needed to fully understand the potential limitations of Llama 3.1.</p><p>Click the following links to deploy Llama 3.1 with BentoML:</p><ul><li><a href="https://github.com/bentoml/BentoVLLM/tree/main/llama3.1-8b-instruct">llama3.1–8b-instruct</a></li><li><a href="https://github.com/bentoml/BentoVLLM/tree/main/llama3.1-70b-instruct-awq">llama3.1–70b-instruct-awq</a></li><li><a href="https://github.com/bentoml/BentoVLLM/tree/main/llama3.1-405b-instruct-awq">llama3.1–405b-instruct-awq</a></li></ul><h3>Mixtral 8x7B</h3><p><a href="https://huggingface.co/mistralai/Mixtral-8x7B-v0.1">Mixtral 8x7B</a>, released by Mistral AI in December 2023, uses a sparse mixture-of-experts architecture. Simply put, it uses many small networks, each specialized in different things. Only a few of these “experts” work on each task, making the process efficient without using the full model’s power every time and thus controlling cost and latency.</p><p>Licensed under the Apache 2.0 license for commercial use, Mixtral 8x7B demonstrates exceptional versatility across various text generation tasks, including code generation, and features a fine-tuned variant, Mixtral 8x7B Instruct, optimized for chat applications.</p><p>Why should you use Mixtral 8x7B:</p><ul><li><strong>State-of-the-art performance:</strong> Mixtral 8x7B outperforms leading models like Llama 2 70B and GPT-3.5 across many benchmarks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Hod3qcaNxvJQ70e.png" /><figcaption>Source: <a href="https://mistral.ai/news/mixtral-of-experts/">https://mistral.ai/news/mixtral-of-experts/</a></figcaption></figure><ul><li><strong>Long context window</strong>: Mixtral 8x7B’s 32k-token context window significantly enhances its ability to handle lengthy conversations and complex documents. This enables the model to handle a variety of tasks, from detailed content creation to sophisticated retrieval-augmented generation, making it highly versatile for both research and commercial applications.</li><li><strong>Optimized for efficiency</strong>: Despite its large parameter count, it offers cost-effective inference, comparable to much smaller models.</li><li><strong>Versatile language support</strong>: Mixtral 8x7B handles multiple languages (French, German, Spanish, Italian, and English), making it ideal for global applications.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lf-8oOJ2wULM799s.png" /><figcaption>Source: <a href="https://mistral.ai/news/mixtral-of-experts/">https://mistral.ai/news/mixtral-of-experts/</a></figcaption></figure><p>Challenges with Mixtral 8x7B:</p><ul><li><strong>Lack of built-in moderation mechanisms</strong>: Without native moderation, there may be a risk of generating inappropriate or harmful content, especially when the model is prompted with sensitive or controversial inputs. Businesses aiming to deploy this model in environments where content control and safety are important should be careful about this.</li><li><strong>Hardware requirements</strong>: The entire parameter set requires substantial RAM for operation, which could limit its use on lower-end systems.</li></ul><p>Quickly serve a Mixtral 8x7B server <a href="https://github.com/bentoml/OpenLLM">with OpenLLM</a> or <a href="https://github.com/bentoml/BentoVLLM/tree/main/mixtral-8x7b-instruct">self-host it with BentoML</a>.</p><h3>Zephyr 7B</h3><p>Zephyr 7B, built on the base of Mistral 7B, has been fine-tuned to achieve better alignment with human intent, outperforming its counterparts in specific tasks and benchmarks. At the time of its release, Zephyr-7B-β is the <a href="https://huggingface.co/HuggingFaceH4/zephyr-7b-beta#performance">highest ranked 7B chat model</a> on the <a href="https://huggingface.co/spaces/lmsys/mt-bench">MT-Bench</a> and <a href="https://tatsu-lab.github.io/alpaca_eval/">AlpacaEval</a> benchmarks.</p><p>Zephyr 7B’s training involves refinement of its abilities through exposure to a vast array of language patterns and contexts. This process allows it to comprehend complex queries and generate coherent, contextually relevant text, making it a versatile tool for content creation, customer support, and more.</p><p>Why should you use Zephyr 7B:</p><ul><li><strong>Efficiency and performance</strong>: Despite its smaller size relative to giants like GPT-3.5 or Llama-2–70B, Zephyr 7B delivers <a href="https://huggingface.co/HuggingFaceH4/zephyr-7b-beta#performance">comparable or superior performance</a>, especially in tasks requiring a deep understanding of human intent.</li><li><strong>Multilingual capabilities</strong>: Trained on a diverse dataset, Zephyr 7B supports text generation and understanding across multiple languages, including but not limited to English, Spanish, French, German, Italian, Portuguese, Dutch, Russian, Chinese, Japanese, and Korean.</li><li><strong>Task flexibility</strong>: Zephyr 7B excels in performing a broad spectrum of language-related tasks, from text generation and summarization to translation and sentiment analysis. This positions it as a highly adaptable tool across numerous applications.</li></ul><p>Challenges with Zephyr 7B:</p><ul><li><strong>Intent alignment</strong>: While Zephyr 7B has made some progress in aligning with human intent, continuous evaluation and adjustment may be necessary to ensure its outputs meet specific user needs or ethical guidelines.</li><li><strong>Adaptation for specialized tasks</strong>: Depending on the application, additional fine-tuning may be required to optimize Zephyr 7B’s performance for specialized tasks, like reasoning, math, and coding.</li></ul><h3>SOLAR 10.7B</h3><p>SOLAR 10.7B is a large language model with 10.7 billion parameters, using an upscaling technique known as depth up-scaling (DUS). This simplifies the scaling process without complex training or inference adjustments.</p><p>SOLAR 10.7B undergoes two fine-tuning stages: <a href="https://ar5iv.labs.arxiv.org/html/2312.15166">instruction tuning and alignment tuning</a>. Instruction tuning enhances its ability to follow instructions in a QA format. Alignment tuning further refines the model to align more closely with human preferences or strong AI outputs, utilizing both open-source datasets and a synthesized math-focused alignment dataset.</p><p>Why should you use SOLAR 10.7B:</p><ul><li><strong>Versatility</strong>: Fine-tuned variants like SOLAR 10.7B-Instruct offer enhanced instruction-following capabilities, making the model capable for a broad range of applications.</li><li><strong>Superior NLP performance</strong>: SOLAR 10.7B demonstrates exceptional performance in NLP tasks, <a href="https://huggingface.co/upstage/SOLAR-10.7B-v1.0#evaluation-results">outperforming other pre-trained models like Llama 2 and Mistral 7B</a>.</li><li><strong>Fine-tuning:</strong> SOLAR 10.7B is an ideal model for fine-tuning with solid baseline capabilities.</li></ul><p>Challenges with SOLAR 10.7B:</p><ul><li><strong>Resource requirements</strong>: The model might require substantial computational resources for training and fine-tuning.</li><li><strong>Bias concerns</strong>: The model’s outputs may not always align with ethical or fair use principles.</li></ul><h3>Code Llama</h3><p>Fine-tuned on Llama 2, Code Llama is an advanced LLM specifically fine-tuned for coding tasks. It’s engineered to understand and generate code across several popular programming languages, including Python, C++, Java, PHP, Typescript (Javascript), C#, and Bash, making it an ideal tool for developers.</p><p>The model is available in four sizes (7B, 13B, 34B, and 70B parameters) to accommodate various use cases, from low-latency applications like real-time code completion with the 7B and 13B models to more comprehensive code assistance provided by the 34B and 70B models.</p><p>Why should you use Code Llama:</p><ul><li><strong>Large input contexts</strong>: Code Llama can handle inputs with up to 100,000 tokens, allowing for better understanding and manipulation of large codebases.</li><li><strong>Diverse applications</strong>: It’s designed for a range of applications such as code generation, code completion, debugging, and even discussing code, catering to different needs within the software development lifecycle.</li><li><strong>Performance</strong>: With models trained on extensive datasets (up to 1 trillion tokens for the 70B model), Code Llama can provide more accurate and contextually relevant code suggestions. The Code Llama — Instruct 70B model even <a href="https://ai.meta.com/blog/code-llama-large-language-model-coding/">scores 67.8 in HumanEval test, higher than GPT 4 (67.0)</a>.</li></ul><p>Challenges with Code Llama:</p><ul><li><strong>Hardware requirements</strong>: Larger models (34B and 70B) may require significant computational resources for optimal performance, potentially limiting access for individuals or organizations with limited hardware.</li><li><strong>Potential for misalignment</strong>: While it has been fine-tuned for improved safety and alignment with human intent, there’s always a risk of generating inappropriate or malicious code if not properly supervised.</li><li><strong>Not for general natural language tasks</strong>: Optimized for coding tasks, Code Llama is not recommended for broader natural language processing applications. Note that only Code Llama Instruct is specifically fine-tuned to better respond to natural language prompts.</li></ul><h3>Why should I choose open-source models over commercial ones?</h3><p>All the language models listed in this blog post are open-source, so I believe this is the very first question to answer. In fact, the choice between open-source and commercial models often depends on specific needs and considerations, but the former may be a better option in the following aspects:</p><ul><li><strong>High controllability</strong>: Open-source models offer a high degree of control, as users can access and refine-tune the model as needed. This allows for customization and adaptability to specific tasks or requirements that might not be possible with commercial models.</li><li><strong>Data security:</strong> Open-source models can be run locally, or within a private cloud infrastructure, giving users more control over data security. With commercial models, there may be concerns about data privacy since the data often needs to be sent to the provider’s servers for processing.</li><li><strong>Cost-effectiveness:</strong> Utilizing open-source models can be more cost-effective, particularly when considering the cost of API calls or tokens required for commercial offerings. Open-source models can be deployed without these recurring costs, though there may be investments needed for infrastructure and maintenance.</li><li><strong>Community and collaboration:</strong> Open-source models benefit from the collective expertise of the community, leading to rapid improvements, bug fixes, and new features driven by collaborative development.</li><li><strong>No vendor lock-in:</strong> Relying on open-source models eliminates dependence on a specific vendor’s roadmap, pricing changes, or service availability.</li></ul><h3>How do specialized LLMs compare to general-purpose models?</h3><p>Specialized LLMs like Code Llama offer a focused performance boost in their areas of specialization. They are designed to excel at specific tasks, providing outputs that are more accurate, relevant, and useful for those particular applications.</p><p>In contrast, general-purpose models like Llama 2 are built to handle a wide range of tasks. While they may not match the task-specific accuracy of specialized models, their broad knowledge base and adaptability make them helpful tools for a variety of applications.</p><p>The choice between specialized and general-purpose LLMs depends on the specific requirements of the task. Specialized models are preferable for high-stakes or niche tasks where precision is more important, while general-purpose models offer better flexibility and broad utility.</p><h3>What are the ethical considerations in deploying LLMs at scale?</h3><p>The ethical deployment of LLMs requires a careful examination of issues such as bias, transparency, accountability, and the potential for misuse. Ensuring that LLMs do not perpetuate existing biases present in their training data is a significant challenge, requiring ongoing vigilance and refinement of training methodologies. Transparency about how LLMs make decisions and the data they are trained on is crucial for building trust and accountability, particularly in high-stakes applications.</p><h3>What should I consider when deploying LLMs in production?</h3><p>Deploying LLMs in production can be a nuanced process. Here are some strategies to consider:</p><ol><li><strong>Choose the right model size</strong>: Balancing the model size with your application’s latency and throughput requirements is essential. Smaller models can offer faster responses and reduced computational costs, while larger models may provide more accurate and nuanced outputs.</li><li><strong>Infrastructure considerations</strong>: Ensure that your infrastructure can handle the computational load. Using cloud services with GPU support or optimizing models with quantization and pruning techniques can help manage resource demands. A serverless platform with autoscaling capabilities can be a good choice for teams without infrastructure expertise.</li><li><strong>Plan for scalability</strong>: Your deployment strategy should allow for scaling up or down based on demand. Containerization with technologies like Docker and orchestration with Kubernetes can support scalable deployments.</li><li><strong>Build robust logging and observability</strong>: Implementing comprehensive logging and observability tools will help in monitoring the system’s health and quickly diagnosing issues as they arise.</li><li><strong>Use APIs for modularity</strong>: APIs can abstract the complexity of model hosting, scaling, and management. They can also facilitate integration with existing systems and allow for easier updates and maintenance.</li><li><strong>Consider model serving frameworks</strong>: Frameworks like BentoML, TensorFlow Serving, TorchServe, or ONNX Runtime can simplify deployment, provide version control, and handle request batching for efficiency.</li></ol><h3>Final thoughts</h3><p>As we navigate the expanding universe of large language models, it’s clear that their potential is only just beginning to be tapped. The rapid innovation in this field signifies a future where AI can contribute even more profoundly to our work and creative endeavors.</p><p>Moving forward, I believe it’s vital to continue promoting AI models in open-source communities, pushing for advances that benefit all and ensuring responsible usage of these powerful tools. As we do so, hopefully, we’ll find the right balance that maximizes the benefits of LLMs for society while mitigating their risks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f2299c86acc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentoml/navigating-the-world-of-large-language-models-8f2299c86acc">Navigating the World of Large Language Models</a> was originally published in <a href="https://medium.com/bentoml">BentoML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Stable Diffusion XL with Latent Consistency Model LoRAs on BentoCloud]]></title>
            <link>https://medium.com/bentoml/deploying-stable-diffusion-xl-with-latent-consistency-model-loras-on-bentocloud-f89a84408f19?source=rss-45268e99b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f89a84408f19</guid>
            <category><![CDATA[latent-consistency-model]]></category>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[bentocloud]]></category>
            <category><![CDATA[bentoml]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <dc:creator><![CDATA[Sherlock Xu]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 00:42:39 GMT</pubDate>
            <atom:updated>2024-05-02T13:19:00.519Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://huggingface.co/papers/2310.04378">Latent Consistency Models (LCM)</a> can be used to streamline the image generation process, particularly for models like Stable Diffusion (SD) and SDXL. In this <a href="https://huggingface.co/blog/lcm_lora">Hugging Face blog post</a>, the authors introduced a new way of integrating <a href="https://arxiv.org/abs/2311.05556">LCM LoRAs</a> into <a href="https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0">SDXL</a>, which allows the model to achieve high-quality inference in just 2 to 8 steps, a significant reduction from its original requirement. This adaptation, or LCM LoRA, represents a universal acceleration module for SD models, making the inference process faster and more accessible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZJHPVJyhdz3QQjmZytVfQ.jpeg" /></figure><p>In this blog post, I will talk about how to wrap SDXL with LCM LoRAs into a BentoML Service and deploy it on BentoCloud. This allows you to better run and manage an image generation application in production.</p><h3>Before you begin</h3><p>The source code of this image generation application powered by SDXL with LCM LoRAs is stored in the <a href="https://github.com/bentoml/BentoLCM">BentoLCM repo</a>. Clone it and install all the required packages.</p><pre>git clone https://github.com/bentoml/BentoLCM.git<br>cd BentoLCM<br>pip install -r requirements.txt</pre><p>Note that this project uses BentoML 1.2.</p><h3>Defining a BentoML Service</h3><p>The key of wrapping the SDXL model and LCM LoRAs with BentoML is to create a BentoML Service. By convention, it is defined in a service.py file.</p><p>First, import the necessary libraries. Add these lines at the top of the service.py file:</p><pre>import bentoml<br>from PIL.Image import Image # For handling images generated by SDXL</pre><p>Specify the models to use. As mentioned above, we are using an <a href="https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0">SDXL model</a> and an <a href="https://huggingface.co/latent-consistency/lcm-lora-sdxl">LCM LoRA</a>. In addition, set a sample prompt so that we can test the application later:</p><pre>model_id = &quot;stabilityai/stable-diffusion-xl-base-1.0&quot;<br>lcm_lora_id = &quot;latent-consistency/lcm-lora-sdxl&quot;<br><br>sample_prompt = &quot;close-up photography of old man standing in the rain at night, in a street lit by lamps, leica 35mm summilux&quot;</pre><p>Now, let’s define a BentoML Service called LatentConsistency. It loads the models and defines an API endpoint for generating images based on text prompts.</p><p>Begin by defining a Python class and its constructor. Starting from BentoML 1.2, we use the @bentoml.service decorator to mark a Python class as a BentoML Service. As the application will be deployed on BentoCloud later, set <a href="https://docs.bentoml.com/en/latest/guides/configurations.html">configurations</a> like resources to specify the GPU to use on BentoCloud.</p><pre># Annotate the class as a BentoML Service with the decorator<br>@bentoml.service(<br>    traffic={&quot;timeout&quot;: 300},<br>    workers=1,<br>    resources={<br>        &quot;gpu&quot;: 1,<br>        &quot;gpu_type&quot;: &quot;nvidia-l4&quot;,<br>    },<br>)<br>class LatentConsistency:<br>    def __init__(self) -&gt; None:<br>        from diffusers import DiffusionPipeline, LCMScheduler<br>        import torch<br>        <br>        # Load the text-to-image model and the LCM LoRA weights<br>        self.lcm_txt2img = DiffusionPipeline.from_pretrained(<br>            model_id,<br>            torch_dtype=torch.float16,<br>            variant=&quot;fp16&quot;,<br>        )<br>        self.lcm_txt2img.load_lora_weights(lcm_lora_id)<br>        # Change the scheduler to the LCMScheduler<br>        self.lcm_txt2img.scheduler = LCMScheduler.from_config(self.lcm_txt2img.scheduler.config)<br>        # Move the model to the GPU for faster inference<br>        self.lcm_txt2img.to(device=&quot;cuda&quot;, dtype=torch.float16)</pre><p>Next, define an API endpoint in your class that takes a text prompt and generates an image:</p><pre>@bentoml.api<br>	def txt2img(<br>	        self,<br>	        prompt: str = sample_prompt,<br>	        num_inference_steps: int = 4,<br>	        guidance_scale: float = 1.0,<br>	) -&gt; Image:<br>	    image = self.lcm_txt2img(<br>	        prompt=prompt,<br>	        num_inference_steps=num_inference_steps,<br>	        guidance_scale=guidance_scale,<br>	    ).images[0]<br>	    return image</pre><p>This function defines an endpoint txt2img that accepts a prompt, number of inference steps, and a guidance scale. It uses Python type annotations to specify the types of parameters it expects and the type of value it returns. The values specified in the code are the defaults provided to users. The returned image is a Path object.</p><p>Note that this example uses 4 inference steps to generate images. This parameter impacts the quality and generation time of the resulting image. See <a href="https://huggingface.co/blog/lcm_lora">this Hugging Face blog post</a> to learn more.</p><p>That’s all! Here is the complete Service code in service.py for your reference (available in the repo cloned):</p><pre>import bentoml<br>from PIL.Image import Image<br><br>model_id = &quot;stabilityai/stable-diffusion-xl-base-1.0&quot;<br>lcm_lora_id = &quot;latent-consistency/lcm-lora-sdxl&quot;<br>sample_prompt = &quot;close-up photography of old man standing in the rain at night, in a street lit by lamps, leica 35mm summilux&quot;<br>@bentoml.service(<br>    traffic={&quot;timeout&quot;: 300},<br>    workers=1,<br>    resources={<br>        &quot;gpu&quot;: 1,<br>        &quot;gpu_type&quot;: &quot;nvidia-l4&quot;,<br>    },<br>)<br>class LatentConsistency:<br>    def __init__(self) -&gt; None:<br>        from diffusers import DiffusionPipeline, LCMScheduler<br>        import torch<br>        self.lcm_txt2img = DiffusionPipeline.from_pretrained(<br>            model_id,<br>            torch_dtype=torch.float16,<br>            variant=&quot;fp16&quot;,<br>        )<br>        self.lcm_txt2img.load_lora_weights(lcm_lora_id)<br>        self.lcm_txt2img.scheduler = LCMScheduler.from_config(self.lcm_txt2img.scheduler.config)<br>        self.lcm_txt2img.to(device=&quot;cuda&quot;, dtype=torch.float16)<br>    @bentoml.api<br>    def txt2img(<br>            self,<br>            prompt: str = sample_prompt,<br>            num_inference_steps: int = 4,<br>            guidance_scale: float = 1.0,<br>    ) -&gt; Image:<br>        image = self.lcm_txt2img(<br>            prompt=prompt,<br>            num_inference_steps=num_inference_steps,<br>            guidance_scale=guidance_scale,<br>        ).images[0]<br>        return image</pre><p>Before deploying, let’s test this Service locally using the BentoML CLI.</p><pre>bentoml serve service:LatentConsistency</pre><p>The command starts the Service at <a href="http://localhost:3000">http://localhost:3000</a>. You can interact with it using the Swagger UI. Alternatively, create a BentoML client as below. As the response is a Path object, you can specify a custom directory to save the image.</p><pre>import bentoml<br>from pathlib import Path<br><br>with bentoml.SyncHTTPClient(&quot;http://localhost:3000&quot;) as client:<br>    result_path = client.txt2img(<br>        guidance_scale=1,<br>        num_inference_steps=4,<br>        prompt=&quot;close-up photography of old man standing in the rain at night, in a street lit by lamps, leica 35mm summilux&quot;,<br>    )<br>    destination_path = Path(&quot;/path/to/save/image.png&quot;)<br>    result_path.rename(destination_path)</pre><p>An example image returned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cc-0tZ9zwB_bJfqz0ipbtQ.png" /></figure><h3>Deploying to BentoCloud</h3><p><a href="https://www.bentoml.com/cloud">BentoCloud</a> provides the underlying infrastructure optimized for running and managing AI applications on the cloud. To deploy this project to BentoCloud, make sure you <a href="https://docs.bentoml.com/en/latest/bentocloud/how-tos/manage-access-token.html">have logged in</a>, then run bentoml deploy in the cloned repo. I added the --scaling-min and --scaling-max flags here to tell BentoCloud the scaling limits of this Deployment, which means it will be scaled within this range according to the traffic received.</p><pre>bentoml deploy . --scaling-min 1 --scaling-max 3</pre><p>After the Deployment is ready, visit its details page on the BentoCloud console and interact with it on the <strong>Playground</strong> tab. This time I changed the prompt as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBDgxaJKR3NdI5klMQJ91w.png" /></figure><p>The generated image can be previewed or downloaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1a7lAGRguoVNTgTuC0yvYg.png" /></figure><h3>Conclusion</h3><p>By wrapping an SDXL model enhanced with LCM LoRA in a BentoML Service, you can rapidly deploy efficient, high-quality image generation AI applications. While the LCM LoRA improves computational efficiency, BentoCloud helps streamline deployment and scaling, ensuring that your application remains responsive regardless of demand.</p><p>In future blog posts, we will see more production-ready AI projects deployed with BentoML and BentoCloud. Happy coding ⌨️!</p><h3>More on BentoML</h3><p>To learn more about BentoML, check out the following resources:</p><ul><li>[Blog] <a href="https://www.bentoml.com/blog/introducing-bentoml-1-2">Introducing BentoML 1.2</a></li><li>[Blog] <a href="https://medium.com/bentoml/deploying-a-text-to-speech-application-with-bentoml-c1e6cbda63e6">Deploying A Text-To-Speech Application with BentoML</a></li><li>[Blog] <a href="https://dzone.com/articles/deploying-an-image-captioning-server-with-bentoml">Deploying An Image Captioning Server With BentoML</a></li><li>[Blog] <a href="https://www.bentoml.com/blog/byoc-to-bentocloud-privacy-flexibility-and-cost-efficiency-in-one-package">BYOC to BentoCloud: Privacy, Flexibility, and Cost Efficiency in One Package</a></li><li>Try <a href="https://www.bentoml.com">BentoCloud</a> and get $10 in free credits on signup! Experience a serverless platform tailored to simplify the building and management of your AI applications, ensuring both ease of use and scalability.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f89a84408f19" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentoml/deploying-stable-diffusion-xl-with-latent-consistency-model-loras-on-bentocloud-f89a84408f19">Deploying Stable Diffusion XL with Latent Consistency Model LoRAs on BentoCloud</a> was originally published in <a href="https://medium.com/bentoml">BentoML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying A Text-To-Speech Application with BentoML]]></title>
            <link>https://medium.com/bentoml/deploying-a-text-to-speech-application-with-bentoml-c1e6cbda63e6?source=rss-45268e99b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1e6cbda63e6</guid>
            <category><![CDATA[bentocloud]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[bentoml]]></category>
            <dc:creator><![CDATA[Sherlock Xu]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 02:52:41 GMT</pubDate>
            <atom:updated>2024-05-02T13:19:31.424Z</atom:updated>
            <content:encoded><![CDATA[<p>Text-to-speech (TTS) technology bridges the gap between written language and its spoken form. By converting text into lifelike speech, TTS enhances user experience across various applications, from aiding visually impaired individuals to providing voice responses in virtual assistants. As developers seek to integrate TTS models into their projects, the process of deploying and managing them efficiently becomes crucial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-phqAYC1wzS6RWdh43eJQ.jpeg" /></figure><p>In this blog post, I will guide you through the steps of deploying a text-to-speech application using BentoML and BentoCloud, powered by the <a href="https://huggingface.co/coqui/XTTS-v2">model XTTS</a>.</p><h3>Before you begin</h3><p>I recommend you create a virtual environment first for dependency isolation.</p><pre>python -m venv bentoxtts<br>source bentoxtts/bin/activate</pre><p>You can find all the code of this project in the <a href="https://github.com/bentoml/BentoXTTS">BentoXTTS</a> repo. Clone the project repo and install the dependencies for this project. Note that this project uses BentoML 1.2.</p><pre>git clone https://github.com/bentoml/BentoXTTS.git<br>cd BentoXTTS<br>pip install -r requirements.txt</pre><h3>v1: Creating a basic text-to-speech script</h3><p>Let’s see what code looks like without BentoML. Initially, you might start with a simple script that leverages a text-to-speech model to convert text into audio. This basic version directly interacts with the TTS API without considering deployment or service architecture. This is the example code I found in the <a href="https://huggingface.co/coqui/XTTS-v2">XTTS</a> Hugging Face repo:</p><pre>from TTS.api import TTS<br><br># Initialize the TTS model with GPU support<br>tts = TTS(&quot;tts_models/multilingual/multi-dataset/xtts_v2&quot;, gpu=True)<br><br># Generate speech from text and save it to a file<br>tts.tts_to_file(text=&quot;It took me quite a long time to develop a voice, and now that I have it I&#39;m not going to be silent.&quot;,<br>                file_path=&quot;output.wav&quot;,<br>                speaker_wav=&quot;/path/to/target/speaker.wav&quot;,<br>                language=&quot;en&quot;)</pre><p>The code should work well but you can’t expose it directly to your users. You need to think about how they can easily interact with it.</p><h3>v2: Integrating BentoML for serving</h3><p>To turn this script into a deployable service, you need to encapsulate the functionality somewhere and preferably expose it as an API endpoint. This is where BentoML comes in.</p><p>The first thing to do is to create a BentoML <a href="https://docs.bentoml.com/en/latest/guides/services.html">Service</a>. Starting from BentoML 1.2, you use the @bentoml.service decorator to annotate a Python class as a BentoML Service. You can add <a href="https://docs.bentoml.com/en/latest/guides/configurations.html">configurations</a> for it to customize the runtime behavior of your Service.</p><p>Let’s call this class XTTS. You can add the tts = TTS(&quot;tts_models/multilingual/multi-dataset/xtts_v2&quot;, gpu=True) part in the v1 code for initialization in this class. Now, you may have something like this:</p><pre>import bentoml<br>import torch<br><br>MODEL_ID = &quot;tts_models/multilingual/multi-dataset/xtts_v2&quot;<br><br># Use the decorator to mark a class as a BentoML Service<br>@bentoml.service(<br>    traffic={&quot;timeout&quot;: 300} # The maximum duration (in seconds) that the Service will wait for a response before timing out.<br>)<br>class XTTS:<br>    def __init__(self) -&gt; None:<br>        # Initialize the TTS model with GPU support based on system availability<br>        self.tts = TTS(MODEL_ID, gpu=torch.cuda.is_available())</pre><p>Next, let’s continue to define an API endpoint. This involves specifying a method (for example, synthesize) within the Service class that will handle requests. In BentoML, you use the @bentoml.api decorator to expose this method as a web endpoint. You can specify the types of input/output that the method will support using type annotations and add sample values as needed. This ensures that the data received by the Service is correctly typed and that users understand what data to provide.</p><p>For this example, you can let the model accept inputs of prompt text and language code and add samples like this:</p><pre>sample_input_data = {<br>    &#39;text&#39;: &#39;It took me quite a long time to develop a voice and now that I have it I am not going to be silent.&#39;,<br>    &#39;language&#39;: &#39;en&#39;,<br>}<br><br>@bentoml.service(<br>    traffic={&quot;timeout&quot;: 300}<br>)<br>class XTTS:<br>    def __init__(self) -&gt; None:<br>        self.tts = TTS(MODEL_ID, gpu=torch.cuda.is_available())<br>    @bentoml.api<br>    def synthesize(<br>          self,<br>          text: str = sample_input_data[&quot;text&quot;],<br>          lang: str = sample_input_data[&quot;language&quot;],<br>     ):</pre><p>With input logic in place, you can proceed to define the output logic of the synthesize method. This involves determining where the synthesized audio file will be stored and handling a sample path.</p><pre>    ...<br>    @bentoml.api<br>    def synthesize(<br>            self,<br>            context: bentoml.Context,<br>            text: str = sample_input_data[&quot;text&quot;],<br>            lang: str = sample_input_data[&quot;language&quot;],<br>    ) -&gt; t.Annotated[Path, bentoml.validators.ContentType(&#39;audio/*&#39;)]:<br>        output_path = os.path.join(context.temp_dir, &quot;output.wav&quot;)<br>        sample_path = &quot;./female.wav&quot;<br>        if not os.path.exists(sample_path):<br>            sample_path = &quot;./src/female.wav&quot;</pre><p>The output logic here tells BentoML that the method returns a path to a file (Path) and that the file is of an audio type (ContentType(&#39;audio/*&#39;)). This guides BentoML in handling the file appropriately when sending it over the network, ensuring that clients understand the format of the data they receive.</p><p>In addition, the Service uses context.temp_dir to create a temporary directory for the output file output.wav and a path to store a sample speaker file (it already exists in the project you cloned). If the sample is not found in the default location, it attempts to locate it under a secondary path.</p><p>Finally, you can integrate the TTS model’s logic to synthesize the audio file based on the input text and language, storing the result in the specified output path.</p><pre>sample_input_data = {<br>    &#39;text&#39;: &#39;It took me quite a long time to develop a voice and now that I have it I am not going to be silent.&#39;,<br>    &#39;language&#39;: &#39;en&#39;,<br>}<br><br>    @bentoml.api<br>    def synthesize(<br>            self,<br>            context: bentoml.Context,<br>            text: str = sample_input_data[&quot;text&quot;],<br>            lang: str = sample_input_data[&quot;language&quot;],<br>    ) -&gt; t.Annotated[Path, bentoml.validators.ContentType(&#39;audio/*&#39;)]:<br>        output_path = os.path.join(context.temp_dir, &quot;output.wav&quot;)<br>        sample_path = &quot;./female.wav&quot;<br>        if not os.path.exists(sample_path):<br>            sample_path = &quot;./src/female.wav&quot;<br><br>        self.tts.tts_to_file(<br>            text,<br>            file_path=output_path,<br>            speaker_wav=sample_path,<br>            language=lang,<br>            split_sentences=True,<br>        )<br>        return Path(output_path)</pre><p>This completes the definition of the synthesize method, which now fully integrates the TTS functionality within a BentoML Service, exposing it as an API endpoint.</p><p>Combining all the steps, you have the complete Service definition in service.py as follows (also available <a href="https://github.com/bentoml/BentoXTTS/blob/main/service.py">here on GitHub</a>):</p><pre>from __future__ import annotations<br><br>import os<br>import typing as t<br>from pathlib import Path<br><br>import bentoml<br><br>MODEL_ID = &quot;tts_models/multilingual/multi-dataset/xtts_v2&quot;<br><br>sample_input_data = {<br>    &#39;text&#39;: &#39;It took me quite a long time to develop a voice and now that I have it I am not going to be silent.&#39;,<br>    &#39;language&#39;: &#39;en&#39;,<br>}<br><br>@bentoml.service(<br>    traffic={&quot;timeout&quot;: 300}<br>)<br>class XTTS:<br>    def __init__(self) -&gt; None:<br>        import torch<br>        from TTS.api import TTS<br><br>        self.tts = TTS(MODEL_ID, gpu=torch.cuda.is_available())<br>    <br>    @bentoml.api<br>    def synthesize(<br>            self,<br>            context: bentoml.Context,<br>            text: str = sample_input_data[&quot;text&quot;],<br>            lang: str = sample_input_data[&quot;language&quot;],<br>    ) -&gt; t.Annotated[Path, bentoml.validators.ContentType(&#39;audio/*&#39;)]:<br>        output_path = os.path.join(context.temp_dir, &quot;output.wav&quot;)<br>        sample_path = &quot;./female.wav&quot;<br>        if not os.path.exists(sample_path):<br>            sample_path = &quot;./src/female.wav&quot;<br><br>        self.tts.tts_to_file(<br>            text,<br>            file_path=output_path,<br>            speaker_wav=sample_path,<br>            language=lang,<br>            split_sentences=True,<br>        )<br>        return Path(output_path)</pre><p>Compared with the v1 code, the v2 code mainly does the following two things:</p><ul><li>Create a BentoML Service to wrap the model.</li><li>Create an API endpoint for the Service with custom input and output logic.</li></ul><p>For the v1 code, you simply copy and paste it in this service.py file.</p><p>To start this BentoML Service locally, run the following command. You may need to set the environment variable COQUI_TTS_AGREED=1 to agree to the terms of Coqui TTS.</p><pre>$ COQUI_TOS_AGREED=1 bentoml serve service:XTTS<br><br>2024-02-08T06:04:10+0000 [WARNING] [cli] Converting &#39;XTTS&#39; to lowercase: &#39;xtts&#39;.<br>2024-02-08T06:04:10+0000 [INFO] [cli] Starting production HTTP BentoServer from &quot;service:XTTS&quot; listening on http://localhost:3000 (Press CTRL+C to quit)</pre><p>You can now interact with the Service at <a href="http://localhost:3000">http://localhost:3000</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WeUUgmHQZQ_9D8QPWTfFig.png" /></figure><p>The expected output is a synthesized audio file of the prompt text based on <a href="https://github.com/bentoml/BentoXTTS/blob/main/female.wav">this sample</a>. The resulting speech mimics the characteristics of the sample voice.</p><h3>Deploying the project in production</h3><p>To run the TTS model in production, I recommend you deploy it to BentoCloud as the serverless platform can manage the underlying infrastructure for you. You only need to focus on your application development.</p><p>First, add resource requirements in the @bentoml.service decorator using the resources field. This allows BentoCloud to automatically schedule the most appropriate instances for deployment.</p><pre>@bentoml.service(<br>    resources={<br>        &quot;gpu&quot;: 1,<br>        &quot;memory&quot;: &quot;8Gi&quot;,<br>    },<br>    traffic={&quot;timeout&quot;: 300},<br>)<br>class XTTS:<br>    def __init__(self) -&gt; None:</pre><p>Next, you need a bentofile.yaml file to define the build configurations for packaging this project into a Bento. bentofile.yaml for this project is already in <a href="https://github.com/bentoml/BentoXTTS/blob/main/bentofile.yaml">the project directory</a>.</p><p>Lastly, no need to manually build a Bento and simply deploy the project by running bentoml deploy. The Bento will be built automatically, then pushed and deployed to BentoCloud. You can also set additional configs like scaling and authorization. See <a href="https://docs.bentoml.com/en/latest/bentocloud/how-tos/create-deployments.html">Create Deployments</a> to learn more.</p><pre>bentoml deploy .</pre><p><strong><em>Note</em></strong><em>: You need to </em><a href="https://www.bentoml.com/cloud"><em>gain access to BentoCloud</em></a><em> and </em><a href="https://docs.bentoml.com/en/latest/bentocloud/how-tos/manage-access-token.html"><em>log in</em></a><em> first.</em></p><p>Once the Deployment is up and running, you can interact with it on the BentoCloud console. I used the <strong>Form</strong> tab to submit a request and the result was displayed on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2cv8fhl37ZOhsum3A0HUQ.png" /><figcaption>BentoCloud playground</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9skuWsNPZZdUs5OCCs6qNw.png" /><figcaption>Deployment info</figcaption></figure><h3>Conclusion</h3><p>In this blog post, we’ve explored how BentoML and BentoCloud simplify the deployment of machine learning models, specifically focusing on creating a text-to-speech Service. I encourage you to experiment with the new concepts of BentoML discussed in this post, explore the capabilities of BentoCloud, and consider creating other innovative AI projects by combining both tools. Happy coding ⌨️!</p><h3>More on BentoML</h3><p>To learn more about BentoML, check out the following resources:</p><ul><li>[Blog] <a href="https://www.bentoml.com/blog/introducing-bentoml-1-2">Introducing BentoML 1.2</a></li><li>[Blog] <a href="https://medium.com/bentoml/deploying-stable-diffusion-xl-with-latent-consistency-model-loras-on-bentocloud-f89a84408f19">Deploying Stable Diffusion XL with Latent Consistency Model LoRAs on BentoCloud</a></li><li>[Blog] <a href="https://dzone.com/articles/deploying-an-image-captioning-server-with-bentoml">Deploying An Image Captioning Server With BentoML</a></li><li>[Blog] <a href="https://www.bentoml.com/blog/byoc-to-bentocloud-privacy-flexibility-and-cost-efficiency-in-one-package">BYOC to BentoCloud: Privacy, Flexibility, and Cost Efficiency in One Package</a></li><li>Try <a href="https://www.bentoml.com">BentoCloud</a> and get $10 in free credits on signup! Experience a serverless platform tailored to simplify the building and management of your AI applications, ensuring both ease of use and scalability.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e6cbda63e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentoml/deploying-a-text-to-speech-application-with-bentoml-c1e6cbda63e6">Deploying A Text-To-Speech Application with BentoML</a> was originally published in <a href="https://medium.com/bentoml">BentoML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Retrieval-Augmented Generation: Part 2]]></title>
            <link>https://medium.com/bentoml/understanding-retrieval-augmented-generation-part-2-b9a40663d145?source=rss-45268e99b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9a40663d145</guid>
            <category><![CDATA[openllm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[bentoml]]></category>
            <dc:creator><![CDATA[Sherlock Xu]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 13:36:58 GMT</pubDate>
            <atom:updated>2024-02-01T14:51:14.589Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second installment of our blog series on Retrieval-Augmented Generation (RAG). In the <a href="https://medium.com/bentoml/understanding-retrieval-augmented-generation-part-1-1f1cea67050b">first article</a>, we explained the fundamentals of RAG, understanding its mechanics and how it combines data retrieval with language generation. We also touched upon the challenges and potential this technology holds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qATckc5qdd-QIOhYfCsP2A.jpeg" /></figure><p>In this article, we will focus on the following three parts and hopefully they can provide you with some insights as you prepare for the <a href="https://rag-a-thon.devpost.com/">LlamaIndex RAG Hackathon</a>.</p><ul><li>Practical applications of RAG.</li><li>Build RAG systems.</li><li>The prospect of RAG.</li></ul><h3>Real-world applications of RAG</h3><p>RAG has practical applications across various industries, impacting how businesses and organizations operate. When designing a RAG system, you may want to consider the needs of real-world scenarios.</p><h4>Research and academia</h4><p>In academia, literature reviews and research may see a new way with RAG. Imagine a system that assists a historian researching the French Revolution. The RAG system scans through hundreds of new academic papers, books, and historical records, summarizing key findings, and even identifying lesser-known but relevant sources, thereby enriching the research process and uncovering new insights.</p><h4>Healthcare</h4><p>In healthcare, RAG’s potential is particularly noteworthy. Medical professionals can use RAG-based systems to stay updated with the latest medical research, treatment protocols, and drug information. This technology can assist in diagnosing diseases or offering treatment recommendations, ensuring that patient care is supported by the most current medical knowledge.</p><h4>Customer service and chatbots</h4><p>In the world of customer service, particularly in chat applications, RAG is redefining the capabilities of chatbots by integrating real-time data for more dynamic interactions. For instance, a chatbot for a basketball league, enhanced with RAG, could offer real-time updates on game scores, player injuries, or post-match analyses. This is particularly valuable for fans following live events or seeking the latest statistics and player performance data. The chatbot, instead of being limited to pre-existing knowledge, becomes a dynamic source of current sports information.</p><h4>Finance and market analysis</h4><p>In finance, a RAG system can be used for real-time market analysis. For example, an investment firm might use RAG to analyze the impact of a sudden political event on market trends. The system can pull in the latest news reports, historical market data, and recent financial analyses, helping analysts quickly understand the event’s implications and make informed investment decisions.</p><p>These examples are only part of what RAG can do for different industries. By leveraging the latest information and contextual data, RAG is not only enhancing existing processes but also creating new possibilities for innovation and efficiency.</p><h3>Building a RAG system</h3><p>There are tons of different ways to build a RAG system. Here are some general points that may help you in its design:</p><ul><li>Use two models in the system — one for text embedding and another as the primary LLM model. This allows for more specialized handling of data retrieval and response generation.</li><li>Integrate OpenLLM and BentoML. You can start your system using any LLM, easily expose API endpoints for interaction, and deploy this system anywhere after containerization. If you are a participant team of the LlamaIndex RAG Hackathon, you will have $100 BentoCloud credits. After you push your project to BentoCloud, you can better manage, monitor and scale it in production.</li><li>Use <a href="https://github.com/vllm-project/vllm">vLLM</a> as the inference backend. vLLM is a high-throughput and memory-efficient inference and serving engine for LLMs. For models with vLLM support, OpenLLM uses vLLM by default.</li><li>The system can start with a small set of initial test data, while it provides users the flexibility to upload their own data to the vector database.</li><li>Consider designing different endpoints for different purposes for interaction with users.</li><li>Consider adding features like automatic data categorization or tagging in the file upload process, enhancing the relevance and accuracy of retrieved information.</li><li>Optimize the vector database for efficient indexing and querying. Fine-tune parameters like index size, search algorithm, and memory usage to balance between speed and accuracy.</li><li>For data-intensive operations like file uploads and embedding generation, implement asynchronous processing to improve system responsiveness and user experience.</li></ul><p>Some resources for your reference:</p><ul><li><a href="https://www.bentoml.com/blog/building-an-intelligent-query-response-system-with-llamaindex-and-openllm">Building An Intelligent Query-Response System with LlamaIndex and OpenLLM</a></li><li><a href="https://docs.bentoml.com/en/v1.1.11/quickstarts/deploy-a-large-language-model-with-openllm-and-bentoml.html">Deploy a large language model with OpenLLM and BentoML</a></li><li><a href="https://github.com/bentoml/OpenLLM">OpenLLM readme</a></li></ul><h3>The future of RAG</h3><p>As RAG technology continues to evolve, its applications are set to become even more sophisticated and impactful. Here are some examples of how RAG might change different aspects of our life in the coming years.</p><h4>Personalized health and wellness coaching</h4><p>In the near future, a RAG-enhanced personal health assistant could offer comprehensive wellness suggestions. For example, after a user inputs their dietary preferences, fitness goals, and current health metrics, the RAG system could analyze a vast array of update-to-date nutritional data, fitness regimes, and medical studies. It might then create a personalized health plan, suggesting specific diets, exercises, and even reminding them to take medications or schedule medical check-ups, all tailored to their unique health profile and goals.</p><h4>Tailored educational experiences</h4><p>In education, a RAG-powered tutoring system could provide students with highly personalized learning experiences. Based on a student’s learning style, progress, and interests, the system could source and integrate educational materials from various platforms, adapt the difficulty level in real time, and offer insights into topics that align with the student’s career goals or personal interests. This helps create a deeply engaging and effective learning environment.</p><h4>Smart home automation</h4><p>In a smart home setting, RAG could take automation to the next level. Imagine a system that not only controls home devices but also anticipates needs based on contextual data. For example, the RAG system could analyze weather forecasts, the homeowner’s schedule, and energy usage patterns to optimize heating and cooling, suggest grocery orders based on consumption trends, and even offer entertainment recommendations based on the user’s mood, interactions and preferences.</p><p>These scenarios demonstrate the remarkable potential of RAG to provide personalized, context-aware solutions. It promises not only to answer our queries but to anticipate our needs and offer solutions that are closely aligned with our personal preferences and life situations.</p><h3>Conclusion</h3><p>The journey ahead for RAG is filled with exciting possibilities. This technology is set to become more intuitive, more adaptive, and even more aligned with individual user needs. Thank you for joining us in this exploration of RAG and good luck to everyone who will be competing in <a href="https://rag-a-thon.devpost.com/">the LlamaIndex RAG Hackathon</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9a40663d145" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentoml/understanding-retrieval-augmented-generation-part-2-b9a40663d145">Understanding Retrieval-Augmented Generation: Part 2</a> was originally published in <a href="https://medium.com/bentoml">BentoML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Retrieval-Augmented Generation: Part 1]]></title>
            <link>https://medium.com/bentoml/understanding-retrieval-augmented-generation-part-1-1f1cea67050b?source=rss-45268e99b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f1cea67050b</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[openllm]]></category>
            <category><![CDATA[llamaindex]]></category>
            <category><![CDATA[bentoml]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Sherlock Xu]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 11:54:06 GMT</pubDate>
            <atom:updated>2024-01-25T11:54:18.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3dyUROiLf3Hc-wXwE-5KQ.png" /></figure><p>Imagine you are a contestant on a competitive cooking show (like <em>Hell’s Kitchen</em>), required to create a dish that’s not only delicious but also tells a unique story. You already have some cooking skills thanks to your past training experience, but what if you could freely access a global library of recipes, regional cooking techniques, and even flavor combinations? That’s where your sous-chef, equipped with a vast culinary database, steps in. This sous-chef doesn’t just bring you ingredients; she also brings specialized knowledge and inspiration, helping you transforming your cooking into a masterpiece that tells a unique, flavorful story.</p><p>This is the essence of Retrieval-Augmented Generation, or RAG in the AI world. Like the sous-chef who elevates your cooking with a wealth of custom resources, RAG enhances the capabilities of large language models (LLMs). It’s not just about responding to queries based on pre-existing knowledge; RAG allows the model to dynamically access and incorporate a vast range of external information, just like tapping into a global culinary database for that unique recipe.</p><p>As a partner of <a href="https://rag-a-thon.devpost.com/">LlamaIndex RAG Hackathon</a>, we will release a two-article blog series about RAG to help the BentoML community gain a better understanding of its concepts and usage. In this first post, we will explore the mechanics of this technology, its benefits, as well as the challenges it faces, offering a comprehensive taste of how RAG is redefining the boundaries of AI interactions.</p><h3>RAG 101</h3><p>Patrick Lewis and his colleagues at Meta first proposed the concept of RAG in the <a href="https://arxiv.org/abs/2005.11401v4">2020 paper Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks</a>. At its core, RAG has two important components: the retrieval system and the language model.</p><ul><li><strong>The retrieval system</strong>: This is like the data corpus of RAG. The retrieval system scans through extensive databases of information to find the most relevant and useful data that can enhance the response to a query. This process is similar to selecting the perfect ingredients for a recipe, ensuring that each one contributes to the final flavor profile.</li><li><strong>The language model</strong>: This is the chef who knows how to combine ingredients into a dish. The language model takes the information sourced by the retrieval system and integrates it into contextually relevant responses.</li></ul><p>Traditional language models are like chefs working with a fixed set of ingredients. They can create impressive dishes (responses) based on what they have (their training data), but they are limited to those ingredients. RAG, on the other hand, has the ability to constantly source new ingredients (information), making dishes (responses) far more diverse, accurate, and rich.</p><h3>Embeddings and vector databases in RAG</h3><p>In the world of RAG, when a user poses a question, it involves a complex computational process, where embeddings and vectors databases play important roles.</p><h3>Embeddings</h3><p>The first step in RAG’s retrieval process involves translating the user’s query into a format that the AI model can understand. This is often done through embeddings or vectors. An embedding is essentially a numeric representation of the query, capturing not just the words, but their context and semantic meaning. Think of it as translating a recipe request into a list of necessary flavor profiles and cooking skills.</p><p><strong><em>Note</em></strong><em>: Previously, we published two blog posts on creating </em><a href="https://www.bentoml.com/blog/deploying-a-sentence-embedding-service-with-bentoml"><em>sentence embedding</em></a><em> and </em><a href="https://www.bentoml.com/blog/building-and-deploying-an-image-embedding-application-with-clip-api-service"><em>image embedding</em></a><em> applications with BentoML respectively. Read them for more details.</em></p><p>Embeddings allow the AI model to process and compare the query against a vast array of stored data efficiently. This process is similar to a chef understanding the essence of a dish and then knowing exactly what ingredients and techniques to use.</p><h3>Vector databases</h3><p>After you have the embeddings, the next crucial component is the vector database.</p><p>Vector databases in RAG store a massive amount of pre-processed information, each piece also represented as embeddings. When the AI model receives a query, it uses these embeddings to search through the database, looking for matches or closely related information.</p><p>The use of vector databases allows RAG to search through and retrieve relevant information with decent speed and precision. It’s like having an instant global connection to different flavors and ingredients, each cataloged not just by name, but by their taste profiles and culinary uses.</p><p>Ultimately, the embeddings, the vector database, and the language model work together to make sure the final response is a well-thought-out answer that blends the retrieved information with the AI’s pre-trained data.</p><h3>The benefits of RAG</h3><p>RAG comes with a number of benefits. To name a few:</p><ul><li><strong>Enhanced accuracy.</strong> By leveraging up-to-date external information, RAG ensures that the answers are not only contextually relevant but also enriched with the latest data. This is particularly important in fields like medicine, technology, and finance.</li><li><strong>Dynamically updated Information</strong>. Unlike traditional models that rely solely on their training data, RAG models can access and incorporate dynamically updated information. Providing the information does not directly modify the underlying language model itself, without incurring any additional training costs.</li><li><strong>Source attribution</strong>: Since the retrieval system knows which documents or text snippets it has pulled from the database, it can provide this information along with the generated response. This provides an extra layer of transparency and trust to the responses generated.</li><li><strong>Personalized interactions</strong>. RAG has the potential for more personalized AI interactions. As the system understands and incorporates specific details from users’ queries, it can provide responses that are more aligned with individual needs and preferences.</li></ul><p>The implications of RAG’s benefits extend far beyond just improved answers. They represent an important shift in how we interact with AI, transforming it into a tool capable of providing informed, accurate, and contextually rich interactions. This opens up new possibilities in education, customer service, research, and any other fields where access to updated, relevant information is important.</p><h3>Challenges and limitations</h3><p>Key challenges of RAG include:</p><ul><li><strong>Data retrieval complexity.</strong> One of the primary challenges in RAG is ensuring the accuracy and relevance of the data retrieved. While RAG is able to pull in vast amounts of information, filtering this data to find the most pertinent pieces can be complex. Ensuring the retrieval system can understand the nuances of different queries is important but not always easy.</li><li><strong>Balancing relevance with reliability</strong>. The retrieval system may have access to a wide range of data, but not all sources are equally trustworthy. Therefore, it is important to balance the relevance of the latest information with the reliability and credibility of sources. This may require developing mechanisms to evaluate and prioritize reliable sources.</li><li><strong>Computational resources and costs</strong>. RAG systems, particularly those handling large datasets and complex queries, require substantial computational resources. The process of retrieving, processing, and integrating external information in real time can be computationally intensive, leading to higher operational costs and potential efficiency concerns.</li><li><strong>Future-proofing</strong>. Ensuring that RAG systems remain effective and up-to-date over time is another challenge. As information sources and user expectations evolve, RAG systems must also adapt and scale accordingly, which requires ongoing development and maintenance.</li></ul><h3>Conclusion</h3><p>Despite these challenges, there is great potential of RAG in transforming AI interactions. Its role in enhancing AI’s capabilities is undeniable, and the journey to refine this technology further is both challenging and exciting.</p><p>In the next article, we will explore the real-world applications of RAG and its future outlook.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f1cea67050b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bentoml/understanding-retrieval-augmented-generation-part-1-1f1cea67050b">Understanding Retrieval-Augmented Generation: Part 1</a> was originally published in <a href="https://medium.com/bentoml">BentoML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>