<?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 Gaurav on Medium]]></title>
        <description><![CDATA[Stories by Gaurav on Medium]]></description>
        <link>https://medium.com/@gaurav021201?source=rss-c2d1674fbf53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HGRfA1Gx32GWfqfCsHH6Zg.jpeg</url>
            <title>Stories by Gaurav on Medium</title>
            <link>https://medium.com/@gaurav021201?source=rss-c2d1674fbf53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:55:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gaurav021201/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 Simple Complex Rag Architecture]]></title>
            <link>https://medium.com/@gaurav021201/a-simple-complex-rag-architecture-c672b74163db?source=rss-c2d1674fbf53------2</link>
            <guid isPermaLink="false">https://medium.com/p/c672b74163db</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Gaurav]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 10:23:44 GMT</pubDate>
            <atom:updated>2024-07-29T10:23:44.515Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: Gaurav Sharma</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BLTFkhkE4QrR92fnrUrVA.jpeg" /></figure><p>RAG (Retrieval-Augmented Generation) is a wrapper around our large language models that combines traditional information retrieval systems and new-day LLMs to produce more accurate, up-to-date, and relevant text that meets your specific needs. It searches through a database to find relevant information and then uses this information to enhance the responses given by the AI model. Rag enables LLMs to retrieve information from relevant data sources and generate responses, even with data not included in their original training data source.</p><p>In this article, we will see what a RAG Architecture could look like in production.</p><h4>How a simple RAG application looks like</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*TkDbv5p_ODTMyMr34NaXAA.png" /></figure><p>A simple RAG application can have a source of information that is processed by an embedding model and stored in a vector database. Later when a user sends over a query, the relevant embeddings are searched from the vector database and a middleware wraps up the prompt with the relevant information. This request is then processed by the AI model and the response is sent back to the user.</p><p>But nowadays the RAG applications are getting bigger and more complex. A lot more processing and optimization goes behind the scenes to generate more accurate and reliable responses from the LLMs. Let’s look into what this complex RAG architecture looks like.</p><h4>A complex RAG Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*vP-n9yqGq7yyZjwge09FiQ.png" /></figure><p>A RAG application in production will have two broad phases of development.</p><ol><li><strong>Data extraction and storage: </strong>Briefly speaking, this process includes processing data collected from large data sources available online (For eg. the Wikipedia dump) and other user-provided data sources like documents and user feedback and storing them in a vector database.</li><li><strong>Query optimization and generation: </strong>Includes all the processes from the time the user&#39;s query lands on our server, to a well-structured response.</li></ol><p>Let’s talk about these in detail one by one.</p><h4>Document text extraction and embedding creation</h4><p>This process is pretty straightforward. An engineer would sit on the internet to find the most relevant data sources that incline towards the specific use case. These would also include user feedback and documents from the audience as well.</p><p>Next, this information is processed and useful information is extracted using small summarization models (GPT 2-small or llama 7B). These embeddings are then chunked and stored in a Vector Database.</p><blockquote>Because of the context length limitations in LLM completion queries and token length limitations in embedding generation models, you will likely need some way to split long text up into smaller chunks.</blockquote><p>A vector database is a type of database that stores and manages unstructured data, such as text, images, or audio, in high-dimensional vectors, to make it easy to find and retrieve similar objects quickly at scale in production.</p><p>They work by using algorithms like vector similarity search to index and query vector embeddings. The importance of vector databases in LLM projects lies in their ability to provide easy search, high performance, scalability, and data retrieval by comparing values and finding similarities between them.</p><h4><strong>Query optimization and generation</strong></h4><p>Now here is where all the engineering and optimization goes. Unlike the simple pipeline in the simple RAG application above, a lot more steps are involved between the user query from the user&#39;s computer to the generation of an AI model. We further split these into 4 steps :</p><h4><strong>Pre-Processing:</strong></h4><p>The prompt submitted by the user is usually a single-line question or a document with a request to summarize it. This can directly hit the LLM and an average response can be returned. However, this is not the case in a RAG application. Each input is tokenized and for a LLM model, there is a maximum limit to the no. of tokens the model can take as input and thus generate a output. For eg, a GPT3.5 model has a token limit of 32k, therefore a document of more than 32k words would probably not fit the context size for your model and it generates nothing as output. Therefore it’s always preferred to filter out the input tokens and pass only the relevant tokens down the pipeline, to save those extra tokens and save them for a quality output. To address this various query re-writing and prompt compression libraries are available like llmlingua and HyDE with RAG.</p><p>After the useful information is extracted from the user’s prompt it goes through a Router which generalizes the request into whether the request requires some document retrieval or needs direct text generation. To address these there are a few types of routing techniques available as follows:</p><ol><li>Semantic Router:</li></ol><p>Each route has a set of example queries associated with it, that become embedded and stored as vectors. The incoming query gets embedded also, and a similarity search is done against the other sample queries from the router. The route which belongs to the query with the closest match gets selected.</p><p>2. Zero-shot text classification:</p><p>This is a task in natural language processing where a model is trained on a set of labeled examples but is then able to classify new examples from previously unseen classes</p><p>3. Language Classification Router</p><p>This type of router is able to identify the language that the query is in, and routes the query based on that. Useful if you require some sort of multilingual parsing abilities in your application.</p><p>4. Logical Routers</p><p>These use logic checks against variables, such as string lengths, file names, and value comparisons to handle how to route a query. They are very similar to typical If/Else conditions used in programming.</p><p>In our use case where we want to route the queries depending on whether it requires document retrieval or normal text generation a semantic router would be helpful.</p><h4>Retrieval:</h4><p>The model performs a search step to collect relevant information from external sources. These sources may include a database, a set of documents, or even search engine results. The search process aims to find text fragments or documents containing information relevant to the given input or request.</p><p>The vector store matches the transformed query against all the embedded documents. It uses similarity metrics to find and retrieve the documents that are most similar to our query. These are the documents most likely to have the information you need. The vector search is done using bi-encoders (like GBERT-bi-encoder) and cross-encoders (like cross-encoder/stsb-roberta-large).</p><p>Once the embeddings are retrieved, these are sorted and parsed to the next step in the pipeline.</p><h4>Augmentation:</h4><p>So now we have the relevant information and our query is also well optimized. In this final step, the information obtained during the retrieval phase is then combined with the original input or prompt and enriched by creating a prompt engineering draft that the model can use to create the output. The model is brought to the format expected by the large language model by including external information in this draft created through prompt engineering.</p><p>Different models have different input formats and it is important to structure the input format according to the model. For eg the input format of mistral and llama models is :</p><pre>&lt;s&gt;[INST] &lt;&lt;SYS&gt;&gt;<br>{{ system_prompt }}<br>&lt;&lt;/SYS&gt;&gt;<br><br>{{ user_message }} [/INST]</pre><p>The prompt thus generated is in the model input format and contains the input prompt wrapped with the retrieved embeddings for the model to generate an accurate and reliable output.</p><h4>Generation:</h4><p>At this point, the system hands over the query prompt to a Large Language Model, or LLM. LLMs, like the ones in the GPT family, are trained on a massive amount of text. This allows them to understand and generate relevant responses and make sense of the current context. The model uses the information from the query prompt to create a well-informed and relevant response.</p><p>In the concluding phase, the response is generated and delivered to you by the system. This response is a blend of the Large Language Model’s overall comprehension and the specific insights gained from pertinent documents.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c672b74163db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Llama 3 ChatBot Part 2: Serving Llama 3 with Langchain]]></title>
            <link>https://medium.com/@gaurav021201/building-llama-3-chatbot-part-1-serving-llama-3-with-langchain-9b37285ebbb8?source=rss-c2d1674fbf53------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b37285ebbb8</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[autogptq]]></category>
            <category><![CDATA[llama-3]]></category>
            <dc:creator><![CDATA[Gaurav]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 11:54:54 GMT</pubDate>
            <atom:updated>2024-04-29T12:10:07.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6bR2YwAFEV3qjlNkCU1hA.jpeg" /></figure><p>In the first part of this blog, we saw how to quantize the Llama 3 model using GPTQ 4-bit quantization. You can continue serving Llama 3 with any Llama 3 quantized model, but if you still prefer getting your own model on the plate and inferencing it, check <a href="https://medium.com/@gaurav021201/building-llama-3-chatbot-part-1-quantization-using-autogptq-0f5bc5abfbcf">part 1</a>.</p><p>Now that the model fits over a single T4 GPU we can put it to test using Langchain.</p><blockquote><strong>LangChain</strong> is a <a href="https://en.wikipedia.org/wiki/Application_framework">framework</a> designed to simplify the creation of <a href="https://en.wikipedia.org/wiki/Application_software">applications</a> using <a href="https://en.wikipedia.org/wiki/Large_language_model">large language models</a> (LLMs). As a language model integration framework, LangChain’s use cases largely overlap with those of language models in general, including document analysis and <a href="https://en.wikipedia.org/wiki/Automatic_summarization">summarization</a>, <a href="https://en.wikipedia.org/wiki/Chatbot">chatbots</a>, and <a href="https://en.wikipedia.org/wiki/Static_program_analysis">code analysis</a>.</blockquote><p>Large Language Models (LLMs) demonstrate significant capabilities but sometimes generate incorrect but believable responses when they lack information, which is known as “<strong>hallucination.</strong>” It means they confidently provide information that may sound accurate but could be incorrect due to outdated knowledge.</p><p><strong>Retrieval-augmented generation or RAG</strong> framework solves this problem by integrating an information retrieval system into the LLM pipeline. Instead of relying on pre-trained knowledge, RAG allows the model to dynamically fetch information from external knowledge sources during inferencing. This dynamic retrieval mechanism ensures that the information provided by the LLM is not only contextually relevant but also accurate and up-to-date.</p><p>To develop the RAG ecosystem in our chatbot we would be using Lanchain pipelines. To get a UI-based chatbot we are using chainlit and Ngrok. If you do not already have an account on Ngrok, get a free account and an API key from <a href="https://ngrok.com/">here</a>.</p><h3>Installing langchain and other other packages</h3><p>Start by installing and loading all the necessary libraries.</p><pre>!pip install -q -U transformers peft accelerate optimum\<br>!pip install auto-gptq<br>!pip install langchain<br>!pip install chainlit</pre><h3>Implementing RAG</h3><p>Next, load the quantized model and the tokenizer</p><pre>%%writefile app.py<br>from langchain.llms import HuggingFacePipeline<br>from langchain.prompts.prompt import PromptTemplate<br>from langchain.chains import ConversationChain<br>from langchain.memory import ConversationBufferWindowMemory<br>import chainlit as cl<br>from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, GPTQConfig<br><br>model_id = &quot;gaurav021201/Meta-Llama-3-8B-GPTQ&quot;<br>quantization_config_loading = GPTQConfig(bits=4, disable_exllama=True)<br>model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config_loading, device_map=&quot;auto&quot;)<br>tokenizer = AutoTokenizer.from_pretrained(model_id)</pre><p>Now implement a pipeline, passing in our model and tokenizer and other basic configurations like max_token_size and device . You can customize the max token size and device according to your needs. You can even read more about pipelines from the <a href="https://huggingface.co/docs/transformers/en/pipeline_tutorial">docs</a>.</p><pre>pipe = pipeline(<br>    task=&quot;text-generation&quot;,<br>    model=model,<br>    tokenizer=tokenizer,<br>    max_new_tokens=512<br>    )<br><br>llm=HuggingFacePipeline(pipeline=pipe)</pre><p>We can now implement a prompt template for our inferencing. A prompt template refers to a reproducible way to generate a prompt. We have created a simple template for our use case, you can generate your own templates according to your use case.</p><pre>template = &quot;&quot;&quot;<br>{history}<br>Question: {input}<br>&quot;&quot;&quot;<br><br>prompt = PromptTemplate(input_variables=[&quot;history&quot;, &quot;input&quot;], template=template)<br>memory=ConversationBufferWindowMemory(k=3)</pre><h3>Setup the Chatbot</h3><p>Now we initialize a Chainlit session, configuring it with a specific conversation chain from <strong>LangChain</strong>. This handles the conversation for each message via Chainlit. It involves receiving a user message, generating a response using LangChain, and sending the response back to the user.</p><pre>@cl.on_chat_start<br>async def start():<br>    llm_chain = ConversationChain(prompt=prompt, llm=llm, memory=memory)<br>    cl.user_session.set(&quot;llm_chain&quot;, llm_chain)<br><br><br>@cl.on_message<br>async def main(message:cl.message):<br>    llm_chain = cl.user_session.get(&quot;llm_chain&quot;)<br>    cb = cl.AsyncLangchainCallbackHandler( )<br>    cb.answer_reached = True<br>    res = await cl.make_async(llm_chain)(message.content, callbacks=[cb])<br>    await cl.Message(content=res[&#39;response&#39;]).send()</pre><h3>Hosting with Ngrok</h3><p>Start by installing pyngrok and setting up the <strong>ngrok</strong> token</p><pre>!pip3 install pyngrok </pre><pre>!ngrok config add-authtoken 2euAA6pePk1rL9Rhxfey604VGP4_Ka5XQBCSUymbNnnEvout</pre><p>To open a tunnel, use the <a href="https://pyngrok.readthedocs.io/en/latest/api.html#pyngrok.ngrok.connect">connect</a> method, which returns a NgrokTunnel, and this returned object has a reference to the public URL generated by ngrok in its public_url attribute.</p><pre>from pyngrok import ngrok<br>print(ngrok.connect(8000).public_url)</pre><p>This will return a HTTPS link which internally points to the localhost of your machine at port 8000.</p><p>Finally, we can launch the Chatbot UI with the Ngrok public URL using the command</p><pre>!chainlit run app.py</pre><p>This will load the Llama 3 model in the GPU memory and be ready for inferencing with RAG implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*VbxeKXJMp11nMRV0heDdXg.png" /></figure><p>As you can see in the above chat conversation from our chatbot, the response is not up to the mark. This is because the model is not yet fine-tuned.</p><blockquote>In deep learning, fine-tuning is an approach to transfer learning in which the parameters of a pre-trained model are trained on new data.</blockquote><p>In further blogs, we will learn how to fine-tune LLM models with our custom data increasing the overall response quality as well as the response time of the model.</p><p>Stay tuned…</p><blockquote><em>Thankyou for reading</em></blockquote><p>Connect with me:</p><p><a href="https://www.linkedin.com/in/gaurav021201/">Linkedin</a> | <a href="https://github.com/grvsh02">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b37285ebbb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Llama 3 ChatBot Part 1: Quantization using AutoGPTQ]]></title>
            <link>https://medium.com/@gaurav021201/building-llama-3-chatbot-part-1-quantization-using-autogptq-0f5bc5abfbcf?source=rss-c2d1674fbf53------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f5bc5abfbcf</guid>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[autogptq]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Gaurav]]></dc:creator>
            <pubDate>Sat, 20 Apr 2024 09:01:15 GMT</pubDate>
            <atom:updated>2024-04-20T09:01:15.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6bR2YwAFEV3qjlNkCU1hA.jpeg" /></figure><p>Meta AI recently released Llama 3, an LLM model, the latest iteration in its series of large language models. As of now Llama 3 is available in 2 different variants, an 8-billion-parameter model and a massive 70-billion-parameter model. These parameters allow it to handle a wide range of use cases, from text generation to complex reasoning tasks.</p><p>As developers and researchers, we now have a powerful tool at our disposal — one that encourages innovation and responsible use. Let’s explore its capabilities and continue building amazing applications with Llama 3.</p><h3><strong>Setup your environment</strong></h3><p>Quantization is crucial in creating a chatbot primarily for optimizing its performance in terms of speed, memory usage, and power consumption.</p><p>We would be using AutoGPTQ 4-bit quantization for this. To get started you will need a jupyter notebook and a GPU with good compute capacity. I am using Kaggle’s free notebook with 2 x Nvidia T4 for this. You can use any preferred platform to get your environment up and running.</p><h3>Installing AutoGPTQ</h3><p>AutoGPTQ installs with CUDA build by default.</p><pre>!pip install auto-gptq</pre><p>Next, let’s install other libraries we will need:</p><pre>pip install optimum<br>pip install transformers<br>pip install accelerate<br>pip install peft</pre><h3>Quantizing Llama 3 8b</h3><p>To get started we will need to authenticate with hugging face APIs to pull the model to our environment.</p><pre>from huggingface_hub import login<br>login()</pre><p>The two main classes currently used in AutoGPTQ are AutoGPTQForCausalLM and BaseQuantizeConfig.</p><pre>from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig</pre><p>To quantize a model, you need to load a pre-trained model and tokenizer first:</p><pre>from transformers import AutoTokenizer, GPTQConfig<br><br>pretrained_model_name = &quot;meta-llama/Meta-Llama-3-8B&quot;<br>tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name)<br>quantize_config = BaseQuantizeConfig(bits=4, group_size=128)<br>model = AutoGPTQForCausalLM.from_pretrained(pretrained_model_name, quantize_config, torch_dtype=torch.float16, low_cpu_mem_usage=True)</pre><p>A few key points to be noted here:</p><ul><li><strong>BaseQuantizeConfig: </strong>you can pass your custom config here with different bits, group sizes,<strong> </strong>desc_act, and seq. length</li><li><strong>AutoGPTQForCausalLM</strong>: we have loaded the model intorch.float16 format which is also the default format, you can use float32 or other formats to load your model.</li></ul><blockquote>The .from_pretrained: by default, loads the whole pre-trained model into the CPU. If you have a limited memory, you can enable the low_cpu_mem_usage or use max_memory to load some model weights to the CPU and other onto GPU only when they’re required to be used, and back to CPU again after that. This is called “CPU offload”, a very useful strategy that is used when there is no room left for quantization or inference if you keep the whole model in GPU(s).</blockquote><p>Now you can start the quantization process</p><pre>token_texts = [<br>    tokenizer(<br>        &quot;RAG is an AI framework for retrieving facts from an external knowledge base to ground large language models (LLMs) on the most accurate, up-to-date information and to give users insight into LLMs&#39; generative process&quot;<br>    )<br>]<br><br>model.quantize(token_texts)</pre><p>Now we can save the quantized model</p><pre>quantized_model_dir = &quot;quantized_model&quot;<br>model.save_quantized(quantized_model_dir, use_safetensors=False)<br># model.save_quantized(quantized_model_dir, use_safetensors=True)</pre><p>By default, the saved file type is .bin, you can also set use_safetensors=True to save a .safetensors model file. Note, that we will anyway need the bin file to inference the model.</p><h3><strong>Push model to hf and inferencing</strong></h3><p>Upload the model to your hf account</p><pre>model.push_to_hub(&quot;gaurav021201/Meta-Llama-3-8B-GPTQ&quot;) # change your hf username</pre><p>Instead of .from_pretrained, you should use .from_quantized to load a quantized model.</p><pre>model = AutoGPTQForCausalLM.from_quantized(quantized_model_dir, device=&quot;cuda:0&quot;)</pre><p>Then you can initialize Transformers TextGenerationPipeline and do inference.</p><pre>from transformers import TextGenerationPipeline<br><br>pipeline = TextGenerationPipeline(model=model, tokenizer=tokenizer)<br>print(pipeline(&quot;auto-gptq is&quot;)[0][&quot;generated_text&quot;])</pre><p>In the next part, we will use this model to inference in our chatbot. Till then stay tuned.</p><blockquote>Thankyou for reading</blockquote><p>Connect with me:</p><p><a href="https://www.linkedin.com/in/gaurav021201/">Linkedin</a> | <a href="https://github.com/grvsh02">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f5bc5abfbcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>