<?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 Nadika Poudel on Medium]]></title>
        <description><![CDATA[Stories by Nadika Poudel on Medium]]></description>
        <link>https://medium.com/@nadikapoudel16?source=rss-202179a107ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SWMiCTJNlNhYbveo</url>
            <title>Stories by Nadika Poudel on Medium</title>
            <link>https://medium.com/@nadikapoudel16?source=rss-202179a107ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:51:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nadikapoudel16/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[Advanced RAG Implementation using Hybrid Search, Reranking with Zephyr Alpha LLM]]></title>
            <link>https://medium.com/@nadikapoudel16/advanced-rag-implementation-using-hybrid-search-reranking-with-zephyr-alpha-llm-4340b55fef22?source=rss-202179a107ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/4340b55fef22</guid>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[hybrid-search]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Nadika Poudel]]></dc:creator>
            <pubDate>Fri, 26 Jan 2024 05:52:08 GMT</pubDate>
            <atom:updated>2024-08-15T02:47:25.725Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced RAG Implementation using Hybrid Search and Reranking</h3><h3>RAG — Retrieval Augmented Generation</h3><p>Let’s say with the limitations of LLMs:</p><ol><li>LLMs tends to hallucinate on its inference with some domain specific data.</li><li>It takes large amount of computing resources to fine-tune LLMs on domain specific knowledge. So,fine-tuning LLMs is very costly.</li><li>A prominent issue with LLMs is their reliance on pre-existing datasets that may not include the most current information. Since these models are trained on data available up to a certain point in time, any developments post-training are not captured in the model’s responses.</li></ol><p><strong>Retrieval-Augmented Generation (RAG)</strong> presents a solution to some of the limitations faced by LLMs. Retrieval Augmented Generation refers to the terminology where we use external data as the context specific data and feed it to the LLM. This data can be domain specific data and fetch it for LLM at inference, this reduce the likelihood of hallucinations.It can also pull data from real-time overcoming the outdated information issue inherent in LLMs and reducing the need of continuos LLM re-training and saving the computational resources.</p><p>Here’s the architecture of RAG system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*lns3qOaTdk_Ue6h3" /><figcaption>Source: <a href="https://blog.griddynamics.com/retrieval-augmented-generation-llm/">https://blog.griddynamics.com/retrieval-augmented-generation-llm/</a></figcaption></figure><p>In this article, we will be implementing Advanced RAG system using following concepts:</p><ol><li>Hybrid Search</li><li>Reranking</li></ol><h3><strong>Hybrid Search</strong></h3><p>Hybrid Search is basically a combination of keyword style search and a vector style search. It has the advantage of doing keyword search as well as the advantage of doing a semantic lookup that we get from embeddings and a vector search.</p><h4>Keyword Search</h4><p>Here we use BM25 Algorithm. It generates a sparse vector.BM25 (Best Match 25) is an information retrieval algorithm used to rank and score the relevance of documents to a particular search query. It’s an extension of the <strong>TF-IDF (Term Frequency-Inverse Document Frequency) approach.</strong></p><h4>Semantic Search</h4><p>Semantic search is a search method that aims to improve the accuracy and relevance of search results by understanding the context and meaning behind a search query. Unlike traditional keyword-based search, which primarily relies on matching keywords, semantic search tries to comprehend the intent and context of the user’s query and the content of the documents being searched.</p><p>In our implementation we have used FAISS for semantic search and BM25 for keyword search to implement Hybrid Search using langchainEnsembleRetriever.</p><h3>Re-ranking</h3><p><strong>Reranking</strong> is a technique that can be used to improve the performance of Retrieval Augmented Generation (RAG) pipelines. In RAG, we perform a semantic search across many text documents, and then use a language model to generate a response. To ensure fast search times at scale, we typically use vector search. However, there is some information loss because we’re compressing this information into a single vector. Because of this information loss, we often see that the top few vector search documents will miss relevant information. Unfortunately, the retrieval may return relevant information below our top_k cutoff. Reranking is one of the simplest methods for dramatically improving recall performance in RAG or any other retrieval-based pipeline. It involves reordering the most relevant items at the top, even though using a better retrieval model is also an option 12.</p><p><strong>Cohere AI Rerankers</strong> is a tool that can be used to implement reranking in a RAG pipeline. It considers relevant context further down the list, enhancing vector search results. Cohere breaks documents into 512 token chunks. For example, if your query is 50 tokens and your document is 1024 tokens, your document will be broken into the following chunks: relevance_score_1 = &lt;query [0,50], document [0,460]&gt; relevance_score_2 = &lt;query [0,50], document [460,920]&gt; relevance_score_3 = &lt;query [0,50],document [920,1024]&gt; 3.</p><p><strong>Contextual Compression</strong> is another technique that can be used to improve document retrieval. Instead of immediately returning retrieved documents as-is, we can compress them using the context of the given query so that only the relevant information is returned. Compressing here refers to both compressing the contents of an individual document and filtering out documents wholesale. The idea is simple: instead of immediately returning retrieved documents as-is, we can compress them using the context of the given query so that only the relevant information is returned.</p><h3><strong>Implementation Stack</strong></h3><h3><strong>1. Dataset:</strong></h3><p>Tech-News dataset from BBC. Here,I have used 110 text documents here but can be increased further.</p><p><a href="http://mlg.ucd.ie/datasets/bbc.html">BBC Datasets</a></p><h3>2. LLM Framework: Langchain</h3><h3><strong>3. RAG Techniques used:</strong></h3><p>Hybrid Search and Re-ranking to retrieve document faster provided with the given context.</p><h3><strong>4. Vector Database: FAISS</strong></h3><p>Vector databases are particularly optimized for similarity search. This means they are capable of quickly finding vectors that are closest (or most similar) to a given query vector.</p><p>FAISS (Facebook AI Similarity Search), developed by Facebook’s AI team is specifically engineered for the efficient similarity search and clustering of dense vectors. FAISS excels in handling large datasets, offering both speed and accuracy in retrieving similar items. This made it an ideal choice for this task that involves searching through large volumes of high-dimensional data i.e. identifying documents relevant to a particular query.</p><h3>5. LLM — Zephyr-7b-alpha</h3><p><a href="https://huggingface.co/HuggingFaceH4/zephyr-7b-alpha">HuggingFaceH4/zephyr-7b-alpha · Hugging Face</a></p><h3>Implementation Details</h3><p>Starting with installation</p><pre>!pip install -q langchain sentence-transformers cohere<br>!pip install faiss-cpu<br>!pip install rank_bm25</pre><p>Importing required libraries</p><pre>from langchain.document_loaders import TextLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.embeddings import HuggingFaceInferenceAPIEmbeddings<br>from langchain.vectorstores import FAISS<br>from langchain.retrievers import ContextualCompressionRetriever<br>from langchain.retrievers.document_compressors import CohereRerank<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough<br>from langchain.retrievers import BM25Retriever, EnsembleRetriever</pre><p>Get the hugging face token</p><pre>import os<br>from getpass import getpass<br><br>HF_token = getpass()<br>os.environ[&#39;HUGGINGFACEHUB_API_TOKEN&#39;] = HF_token</pre><p>Import dataset</p><pre>dataset_folder_path=&#39;/content/drive/MyDrive/Tech_news_dataset/dataset_news/&#39;<br>documents=[]<br>for file in os.listdir(dataset_folder_path):<br>  loader=TextLoader(dataset_folder_path+file)<br>  documents.extend(loader.load())<br>documents[:3]</pre><p>Chunking the document/text</p><pre>text_splitter=RecursiveCharacterTextSplitter(chunk_size=512,chunk_overlap=50)<br>text_splits=text_splitter.split_documents(documents)<br>print(len(text_splits))</pre><h4><strong>Embedding Model</strong></h4><pre>embeddings=HuggingFaceInferenceAPIEmbeddings(<br>    api_key=HF_token,<br>    model_name=&#39;BAAI/bge-base-en-v1.5&#39;<br>)</pre><p>Enabling the vector database</p><pre>vectorstore = FAISS.from_documents(text_splits, embeddings)</pre><h3><strong>Implementing Hybrid Search with ensemble Retrieval</strong></h3><pre>retriever_vectordb = vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 5})<br>keyword_retriever = BM25Retriever.from_documents(text_splits)<br>keyword_retriever.k =  5<br>ensemble_retriever = EnsembleRetriever(retrievers=[retriever_vectordb,keyword_retriever],<br>                                       weights=[0.5, 0.5])<br><br>query=&quot;How many cafes were closed in 2004?&quot;<br>docs_rel=ensemble_retriever.get_relevant_documents(query)<br>docs_rel<br><br>&quot;&quot;&quot;OUTPUT<br>[Document(page_content=&quot;China net cafe culture crackdown\n\nChinese authorities closed 12,575 net cafes in the closing months of 2004, the country&#39;s government said.&quot;, metadata={&#39;source&#39;: &#39;/content/drive/MyDrive/Tech_news_dataset/dataset_news/002.txt&#39;}),<br> Document(page_content=&#39;According to the official news agency most of the net cafes were closed down because they were operating illegally. Chinese net cafes operate under a set of strict guidelines and many of those most recently closed broke rules that limit how close they can be to schools. The move is the latest in a series of steps the Chinese government has taken to crack down on what it considers to be immoral net use.&#39;, metadata={&#39;source&#39;: &#39;/content/drive/MyDrive/Tech_news_dataset/dataset_news/002.txt&#39;}),<br> Document(page_content=&#39;The official Xinhua News Agency said the crackdown was carried out to create a &quot;safer environment for young people in China&quot;. Rules introduced in 2002 demand that net cafes be at least 200 metres away from middle and elementary schools. The hours that children can use net cafes are also tightly regulated. China has long been worried that net cafes are an unhealthy influence on young people. The 12,575 cafes were shut in the three months from October to December. China also tries to dictate the types of&#39;, metadata={&#39;source&#39;: &#39;/content/drive/MyDrive/Tech_news_dataset/dataset_news/002.txt&#39;}),<br> Document(page_content=&#39;Net cafes are hugely popular in China because the relatively high cost of computer hardware means that few people have PCs in their homes. This is not the first time that the Chinese government has moved against net cafes that are not operating within its strict guidelines. All the 100,000 or so net cafes in the country are required to use software that controls what websites users can see. Logs of sites people visit are also kept. Laws on net cafe opening hours and who can use them were introduced in 2002&#39;, metadata={&#39;source&#39;: &#39;/content/drive/MyDrive/Tech_news_dataset/dataset_news/002.txt&#39;}),<br> Document(page_content=&#39;and who can use them were introduced in 2002 following a fire at one cafe that killed 25 people. During the crackdown following the blaze authorities moved to clean up net cafes and demanded that all of them get permits to operate. In August 2004 Chinese authorities shut down 700 websites and arrested 224 people in a crackdown on net porn. At the same time it introduced new controls to block overseas sex sites. The Reporters Without Borders group said in a report that Chinese government technologies for&#39;, metadata={&#39;source&#39;: &#39;/content/drive/MyDrive/Tech_news_dataset/dataset_news/002.txt&#39;}),<br> Document(page_content=&#39;Already net use in China has a very different character than in many Western nations, said William Makower, chief executive of Panlogic. In many Western nations desktop computers that can access the net are hard to escape at work. By contrast in China workplace machines are relatively rare. This, combined with the relatively high cost of PCs in China and the time it takes to get phone lines installed, helps to explains the huge number of net cafes in China. Only 36% of Chinese homes have telephones&#39;, metadata={&#39;source&#39;: &#39;/content/drive/MyDrive/Tech_news_dataset/dataset_news/074.txt&#39;})]<br>&quot;&quot;&quot;<br></pre><p>LLM Model</p><pre>from langchain.llms import HuggingFaceHub<br>model=HuggingFaceHub(repo_id=&#39;HuggingFaceH4/zephyr-7b-alpha&#39;,<br>                     model_kwargs={&quot;temperature&quot;:0.5,&quot;max_new_tokens&quot;:512,&quot;max_length&quot;:64}<br>)</pre><h3>Implementing Re-ranking with Cohere-Rerank</h3><pre>Cohere_API_token = getpass()<br>os.environ[&quot;COHERE_API_KEY&quot;] =Cohere_API_token<br><br>compressor = CohereRerank()<br>compression_retriever = ContextualCompressionRetriever(<br>    base_compressor=compressor, base_retriever=ensemble_retriever<br>)<br>compressed_docs = compression_retriever.get_relevant_documents(query)<br>compressed_docs<br><br><br>&quot;&quot;&quot; OUTPUT<br>[Document(page_content=&quot;China net cafe culture crackdown\n\nChinese authorities closed 12,575 net cafes in the closing months of 2004, the country&#39;s government said.&quot;, metadata={&#39;source&#39;: &#39;/content/drive/MyDrive/Tech_news_dataset/dataset_news/002.txt&#39;, &#39;relevance_score&#39;: 0.9984022}),<br> Document(page_content=&#39;According to the official news agency most of the net cafes were closed down because they were operating illegally. Chinese net cafes operate under a set of strict guidelines and many of those most recently closed broke rules that limit how close they can be to schools. The move is the latest in a series of steps the Chinese government has taken to crack down on what it considers to be immoral net use.&#39;, metadata={&#39;source&#39;: &#39;/content/drive/MyDrive/Tech_news_dataset/dataset_news/002.txt&#39;, &#39;relevance_score&#39;: 0.98469365}),<br> Document(page_content=&#39;The official Xinhua News Agency said the crackdown was carried out to create a &quot;safer environment for young people in China&quot;. Rules introduced in 2002 demand that net cafes be at least 200 metres away from middle and elementary schools. The hours that children can use net cafes are also tightly regulated. China has long been worried that net cafes are an unhealthy influence on young people. The 12,575 cafes were shut in the three months from October to December. China also tries to dictate the types of&#39;, metadata={&#39;source&#39;: &#39;/content/drive/MyDrive/Tech_news_dataset/dataset_news/002.txt&#39;, &#39;relevance_score&#39;: 0.9797453})]<br>&quot;&quot;&quot;<br></pre><h3>Augmentation and Generation</h3><pre>template = &quot;&quot;&quot;<br>&lt;|system|&gt;&gt;<br>You are an AI Assistant that follows instructions extremely well.<br>Please be truthful and give direct answers. Please tell &#39;I don&#39;t know&#39; if user query is not in CONTEXT<br><br>CONTEXT: {context}<br>&lt;/s&gt;<br>&lt;|user|&gt;<br>{query}<br>&lt;/s&gt;<br>&lt;|assistant|&gt;<br>&quot;&quot;&quot;<br><br>prompt = ChatPromptTemplate.from_template(template)<br>output_parser = StrOutputParser()<br><br>chain = (<br>    {&quot;context&quot;: compression_retriever, &quot;query&quot;: RunnablePassthrough()}<br>    | prompt<br>    | model<br>    | output_parser<br>)</pre><pre>query=&quot;How many cafes were closed in 2004 in China?&quot;<br>response = chain.invoke(query)<br>response<br><br><br>&quot;&quot;&quot;<br>OUTPUT<br><br>According to the context provided, 12,575 net cafes were closed in the closing months of 2004 in China.<br><br>&quot;&quot;&quot;<br></pre><p>Access Colab Notebook on: <a href="https://colab.research.google.com/drive/1IdIVS7-y22gqdvshUiQ18ybw0RqUpWaH#scrollTo=0r8AkIok4L88">https://colab.research.google.com/drive/1IdIVS7-y22gqdvshUiQ18ybw0RqUpWaH#scrollTo=0r8AkIok4L88</a></p><h3>Demo on Streamlit</h3><p>Find the full code at Github for creating demo on Streamlit:</p><p><a href="https://github.com/Nadika18/RAG-TechnewsChatbot">GitHub - Nadika18/RAG-TechnewsChatbot: This chatbot is created using Langchain, Zephyr LLMs and concept of RAG.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*QcUJlCfTodZaApL4IhdfxA.png" /><figcaption>Demo on Stremlit</figcaption></figure><h3>Additional notes:</h3><ol><li><strong>Making sure the model does not hallucinate:</strong></li></ol><p>I tried checking on something not mentioned on dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*yxOdPR64pQ8AD2AxT4TeSg.png" /><figcaption>No hallucination</figcaption></figure><p>It was done with prompt engineering, giving randomness to the model with temperature and with reranking.</p><h3>References:</h3><ul><li><a href="https://medium.aiplanet.com/advanced-rag-implementation-on-custom-data-using-hybrid-search-embed-caching-and-mistral-ai-ce78fdae4ef6">Advanced RAG Implementation on Custom Data Using Hybrid Search, Embed Caching And Mistral-AI</a></li><li><a href="https://medium.aiplanet.com/advanced-rag-cohere-re-ranker-99acc941601c">Advanced RAG- Cohere Re-Ranker</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4340b55fef22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finetuning Zephyr 7B with QLoRa and PERF for Customer Support Chatbot]]></title>
            <link>https://medium.com/@nadikapoudel16/finetuning-zephyr-7b-with-qlora-and-perf-for-customer-support-chatbot-57a52d95b7aa?source=rss-202179a107ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/57a52d95b7aa</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[qlora]]></category>
            <category><![CDATA[finetune-llm]]></category>
            <category><![CDATA[zephyr]]></category>
            <dc:creator><![CDATA[Nadika Poudel]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 10:23:19 GMT</pubDate>
            <atom:updated>2024-01-01T10:23:19.987Z</atom:updated>
            <content:encoded><![CDATA[<p>Here, I am talking about how I trained a quantized Zephyr-7B-beta LLM model using Google Colab’s free tier T4 GPU using the concepts of QLoRa and PERF.</p><h4>About Zephyr 7B β</h4><p>Zephyr-7B-β is the second model in the series, and is a fine-tuned version of <a href="https://huggingface.co/mistralai/Mistral-7B-v0.1">mistralai/Mistral-7B-v0.1</a> that was trained on on a mix of publicly available, synthetic datasets using <a href="https://arxiv.org/abs/2305.18290">Direct Preference Optimization (DPO)</a>.</p><p><strong>Model description</strong></p><ul><li>Model type: A 7B parameter GPT-like model fine-tuned on a mix of publicly available, synthetic datasets.</li><li>Language(s) (NLP): Primarily English</li><li>License: MIT</li><li>Finetuned from model: <a href="https://huggingface.co/mistralai/Mistral-7B-v0.1">mistralai/Mistral-7B-v0.1</a></li></ul><h3>QLoRA</h3><p><strong>QLoRA </strong>is a fine-tuning method that combines Quantization and Low-Rank Adapters (LoRA). QLoRA is revolutionary in that it democratizes fine-tuning: it enables one to fine-tune massive models with billions of parameters on relatively small, highly available GPUs.</p><p><strong>Quantization </strong>in the context of deep learning is the process of reducing the numerical precision of a model’s tensors, making the model more compact and the operations faster in execution. Quantization maps high-precision floating points to lower-precision values, usually 8- or even 4-bit fixed-point representation integers. This reduce tensor sizes by 75% or even 87.5%, but usually results in a significant reduction in model accuracy; however, it may also help the model generalize better, so experimentation may be worthwhile.</p><p><strong>LoRA</strong>, which stands for “Low Rank Adaptation,” is a <a href="https://arxiv.org/abs/2106.09685">method</a> designed to fine-tune large pre-trained language models more efficiently by reducing the number of trainable parameters.Fine-tuning usually involves updating the entire set of parameters in the model, which can be computationally expensive and time-consuming for large language models. LoRA makes this process more efficient by creating and updating low-rank approximations of the original weight matrices (called update matrices) which are formed using low-rank decomposition on the original weight matrix. Only these matrices are updated during fine-tuning — the original model weights remain the same — and thus LoRA’s total number of trainable parameters is equal to the size of the low-rank update matrices. Since the low-rank matrices are being updated instead of all of the larger matrices with far more parameters, we can do this on a smaller, cheaper GPU.</p><p><strong>PEFT</strong> is a library designed for efficient fine-tuning of pre-trained language models. Fine-tuning models can be resource-intensive, especially when dealing with large-scale pre-trained models. PEFT addresses this challenge by focusing on fine-tuning only a small subset of parameters, thus reducing computational and storage costs.</p><p>Now, lets dive into the <strong>implementation</strong>. First lets install and import the dependencies.</p><pre>!pip install -qU transformers accelerate bitsandbytes trl peft datasets auto-gptq optimum<br>!pip install -qU streamlit streamlit-chat</pre><pre>import torch<br>from transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig, TrainingArguments,GenerationConfig, AutoTokenizer,BitsAndBytesConfig<br>from datasets import load_dataset,Dataset<br>from sklearn.model_selection import train_test_split<br>from trl import SFTTrainer<br>from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model,AutoPeftModelForCausalLM</pre><p>We’ll be using <a href="https://huggingface.co/TheBloke/zephyr-7B-beta-GPTQ">https://huggingface.co/TheBloke/zephyr-7B-beta-GPTQ</a> model.</p><pre>base_model=&quot;TheBloke/zephyr-7B-beta-GPTQ&quot;</pre><p>Now, lets downloading the dataset, and then do a little preprocessing.</p><p>This <strong>dataset</strong> contains over 26,000 question/answer pairs from 27 common intents in the customer service domain, such as password recovery, delivery options, track refund, registration issues, etc. It includes 30 entity/slot types and 12 different types of language generation tags to help the chatbot produce natural and relevant responses</p><pre>dataset_name=&quot;bitext/Bitext-customer-support-llm-chatbot-training-dataset&quot;<br><br>dataset=load_dataset(dataset_name,split=&#39;train&#39;)<br># Convert to pandas DataFrame<br>df_train = dataset.to_pandas()<br># Split the training data into train and validation sets<br>train_data, eval_data = train_test_split(df_train, test_size=0.2, random_state=42)<br><br><br>#perform preprocessing<br>def data_preprocessing(text):<br>  # function to process the dataset sample by adding prompt and clean if necessary.<br>  processed_text = &quot;&lt;|system|&gt;\n You are a support chatbot who helps with user queries chatbot who always responds in the style of a professional.\n&lt;|user|&gt;\n&quot; + text[&quot;instruction&quot;] + &quot;\n&lt;|assistant|&gt;\n&quot; + text[&quot;response&quot;]<br>  return {&quot;text&quot;: processed_text}<br><br><br><br># Apply processing function to each row using apply_rows<br>train_dataset = Dataset.from_pandas(train_data).map(data_preprocessing)<br>eval_dataset = Dataset.from_pandas(eval_data).map(data_preprocessing)<br><br><br># Print the first few rows to verify the preprocessing<br>print(train_dataset[&quot;text&quot;][:5])<br>print(eval_dataset[&quot;text&quot;][:5])</pre><p>In the next step, we will download a 4 bit model and tokenizer onto our GPU.</p><pre># Get tokenizer<br>tokenizer=AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)<br>tokenizer.padding_side = &#39;right&#39;<br>tokenizer.pad_token = tokenizer.eos_token<br>tokenizer.add_eos_token = True<br>tokenizer.add_bos_token, tokenizer.add_eos_token<br><br><br>bnb_config = GPTQConfig(bits=4,<br>                        disable_exllama=True,<br>                        device_map=&quot;auto&quot;,<br>                        use_cache=False,<br>                        lora_r=16,<br>                        lora_alpha=16,<br>                        tokenizer=tokenizer<br>                                )<br><br># Get quantized model<br>model = AutoModelForCausalLM.from_pretrained(<br>    base_model,<br>    device_map=&quot;auto&quot;,<br>    trust_remote_code=True,<br>    quantization_config=bnb_config,<br>)<br><br><br>model.config.use_cache = False<br>model.config.pretraining_tp = 1<br>model.gradient_checkpointing_enable()<br>model = prepare_model_for_kbit_training(model)<br>print(model)</pre><p>Now let’s add the <strong>LoRA </strong>adapter on top with <strong>PEFT</strong>.</p><pre># preparing model for finetuning<br>peft_config = LoraConfig(<br>                            r=16,<br>                            lora_alpha=16,<br>                            lora_dropout=0.05,<br>                            bias=&quot;none&quot;,<br>                            task_type=&quot;CAUSAL_LM&quot;,<br>                            target_modules=[&quot;q_proj&quot;, &quot;v_proj&quot;]<br>                        )<br><br>model = get_peft_model(model, peft_config)<br>print(model)</pre><h3>Training the Model</h3><p>It’s important to set the correct hyperparameters in the training arguments. Then, we will use HuggingFace’s TRL library to build the SFT Trainer with necessary components such as model, dataset, Lora configuration, tokenizer, and training parameters.</p><p>In the end, we will start training.</p><pre>OUTPUT_DIR=&#39;zephyr-finetuning&#39;<br>OPTIMIZER = &quot;paged_adamw_32bit&quot;<br><br>training_arguments = TrainingArguments(<br>                                        output_dir=OUTPUT_DIR,<br>                                        per_device_train_batch_size=8,<br>                                        gradient_accumulation_steps=1,<br>                                        optim=OPTIMIZER,<br>                                        learning_rate=2e-4,<br>                                        lr_scheduler_type=&quot;cosine&quot;,<br>                                        save_strategy=&quot;epoch&quot;,<br>                                        logging_steps=50,<br>                                        num_train_epochs=1,<br>                                        max_steps=100,<br>                                        fp16=True,<br>                                        evaluation_strategy=&quot;steps&quot;,<br>                                        eval_steps=50,<br>                                        push_to_hub=False)<br>#finetuning<br>trainer = SFTTrainer(<br>                        model=model,<br>                        train_dataset=train_dataset,<br>                        eval_dataset=eval_dataset,<br>                        peft_config=peft_config,<br>                        dataset_text_field=&quot;text&quot;,<br>                        args=training_arguments,<br>                        tokenizer=tokenizer,<br>                        packing=False,<br>                        max_seq_length=1024<br>                    )<br><br>trainer.train()</pre><p>After almost 1.5 hour, fine-tuning was completed and I could observe a gradual reduction in the training and validation loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*T7fb1eytefcLIdLfMzxMFg.png" /></figure><h4>Perform Inference using the finetuned model</h4><pre>#data preprocessing for the sample input data<br>def input_data_preprocessing(example):<br><br>    processed_example = &quot;&lt;|system|&gt;\n You are a support chatbot who helps with user queries chatbot who always responds in the style of a professional.\n&lt;|user|&gt;\n&quot; + example[&quot;instruction&quot;] + &quot;\n&lt;|assistant|&gt;\n&quot;<br><br>    return processed_example<br>input_string = input_data_preprocessing(<br>    {<br>        &quot;instruction&quot;: &quot;i have a question about cancelling order {{Order Number}}&quot;,<br>    }<br>)<br><br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;/content/zephyr-finetuning/checkpoint-200&quot;)<br><br><br>model = AutoPeftModelForCausalLM.from_pretrained(<br>    &quot;/content/zephyr-finetuning/checkpoint-200&quot;,<br>    low_cpu_mem_usage=True,<br>    return_dict=True,<br>    torch_dtype=torch.float16,<br>    device_map=&quot;cuda&quot;)<br><br>inputs = tokenizer(input_string, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br><br>generation_config = GenerationConfig(<br>    do_sample=True,<br>    top_k=1,<br>    temperature=0.1,<br>    max_new_tokens=256,<br>    pad_token_id=tokenizer.eos_token_id<br>)<br><br>outputs = model.generate(**inputs, generation_config=generation_config)<br>print(tokenizer.decode(outputs[0], skip_special_tokens=True))</pre><p>Now, let&#39;s create a simple demo app using Streamlit.I created the bot with the fine-tuned Zephyr model and inferred responses from the model based on user input.</p><pre>#zipping model files to save in local<br><br>import locale<br>locale.getpreferredencoding = lambda: &quot;UTF-8&quot;<br><br>!zip -r zephyr-finetuning.zip zephyr-finetuning</pre><pre><br>%%writefile app.py<br>from peft import AutoPeftModelForCausalLM<br>from transformers import GenerationConfig<br>from transformers import AutoTokenizer<br>import torch<br>import streamlit as st<br>from streamlit_chat import message<br><br>st.session_state.clicked=True<br><br>def process_data_sample(example):<br><br>    processed_example = &quot;&lt;|system|&gt;\n You are a support chatbot who helps with user queries chatbot who always responds in the style of a professional.&lt;/s&gt;\n&lt;|user|&gt;\n&quot; + example + &quot;&lt;/s&gt;\n&lt;|assistant|&gt;\n&quot;<br><br>    return processed_example<br><br>@st.cache_resource(show_spinner=True)<br>def create_bot():<br><br>    tokenizer = AutoTokenizer.from_pretrained(&quot;/content/zephyr-finetuning/checkpoint-100&quot;)<br><br>    model = AutoPeftModelForCausalLM.from_pretrained(<br>                                                        &quot;/content/zephyr-finetuning/checkpoint-100&quot;,<br>                                                        low_cpu_mem_usage=True,<br>                                                        return_dict=True,<br>                                                        torch_dtype=torch.float16,<br>                                                        device_map=&quot;cuda&quot;<br>                                                    )<br><br>    generation_config = GenerationConfig(<br>                                            do_sample=True,<br>                                            temperature=0.5,<br>                                            max_new_tokens=256,<br>                                            pad_token_id=tokenizer.eos_token_id<br>                                        )<br><br>    return model, tokenizer, generation_config<br><br>model, tokenizer, generation_config = create_bot()<br><br>bot = create_bot()<br><br>def infer_bot(prompt):<br>    inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br>    outputs = model.generate(**inputs, generation_config=generation_config)<br>    out_str = tokenizer.decode(outputs[0], skip_special_tokens=True).replace(prompt, &#39;&#39;)<br>    return out_str<br><br>def display_conversation(history):<br>    for i in range(len(history[&quot;assistant&quot;])):<br>        message(history[&quot;user&quot;][i], is_user=True, key=str(i) + &quot;_user&quot;)<br>        message(history[&quot;assistant&quot;][i],key=str(i))<br><br>def main():<br><br>    st.title(&quot;Zephyr fine-tuned chatbot &quot;)<br>    st.subheader(&quot;A bot created using Zephyr which was finetuned to possess the capabilities to be a support member&quot;)<br><br>    user_input = st.text_input(&quot;Enter your query&quot;)<br><br>    if st.session_state.clicked:<br>        if st.button(&quot;Answer&quot;):<br><br>            answer = infer_bot(user_input)<br>            st.session_state[&quot;user&quot;].append(user_input)<br>            st.session_state[&quot;assistant&quot;].append(answer)<br><br>            if st.session_state[&quot;assistant&quot;]:<br>                display_conversation(st.session_state)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()<br></pre><p>Now,I set up Cloudflare’s cloudflared tool to create a secure tunnel for locally running Streamlit app. This makes the app accessible via a secure HTTPS URL provided by Cloudflare.</p><pre>!wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64<br>!chmod +x cloudflared-linux-amd64<br>!nohup /content/cloudflared-linux-amd64 tunnel --url http://localhost:8501 &amp;</pre><pre>!grep -o &#39;https://.*\.trycloudflare.com&#39; nohup.out | head -n 1 | xargs -I {} echo &quot;Your tunnel url {}&quot;</pre><pre>!streamlit run /content/app.py &amp;&gt;/content/logs.txt &amp;</pre><p>So, our customer support Chatbot is ready !!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*naQIkv4D7QwNzM7dDqg4Ig.png" /></figure><p><strong>Additional info:</strong></p><p>You can increase max_steps for better performance.</p><h3><strong>References:</strong></h3><ul><li><a href="https://huggingface.co/TheBloke/zephyr-7B-beta-GPTQ">TheBloke/zephyr-7B-beta-GPTQ · Hugging Face</a></li><li><a href="https://gathnex.medium.com/fine-tuning-llama-2-llm-on-google-colab-a-step-by-step-guide-dd79a788ac16">Fine-Tuning Llama-2 LLM on Google Colab: A Step-by-Step Guide.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57a52d95b7aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>