<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Denken</title>
	<atom:link href="https://www.aritrasen.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.aritrasen.com</link>
	<description></description>
	<lastBuildDate>Mon, 11 Sep 2023 12:02:57 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.3.8</generator>
	<item>
		<title>Announcement: Launch of my YouTube channel focused on Data Science</title>
		<link>https://www.aritrasen.com/announcement-launch-of-my-youtube-channel-focused-on-data-science/</link>
					<comments>https://www.aritrasen.com/announcement-launch-of-my-youtube-channel-focused-on-data-science/#respond</comments>
		
		<dc:creator><![CDATA[Aritra Sen]]></dc:creator>
		<pubDate>Mon, 11 Sep 2023 12:02:21 +0000</pubDate>
				<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Announcements]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[YouTubeChannel]]></category>
		<guid isPermaLink="false">https://www.aritrasen.com/?p=1059</guid>

					<description><![CDATA[Want to get rid of Monday morning blues!! Need a refresher in Python for Data Science!! Here is something can help &#8230; Happy to launch my YouTube channel with first series of tutorials with bare minimum python you need to get started with Data Science. Series contains 7 video tutorials with the below mentioned topics...]]></description>
										<content:encoded><![CDATA[
<p>Want to get rid of Monday morning blues!! Need a refresher in Python for Data Science!! Here is something can help &#8230;</p>



<p>Happy to launch my YouTube channel with first series of tutorials with bare minimum python you need to get started with Data Science. Series contains 7 video tutorials with the below mentioned topics &#8211;</p>



<p>1. Python variables and datatypes <br>2. Datatype conversation and different type of loops<br>3. Functions, Scope of Variables, Lambda Functions<br>4. Sorting List, Tuple, Dictionary &amp; Zip Function<br>5. Class and Instances (Basics of OOPs)<br>6. NumPy<br>7. Pandas</p>



<p>Channel link &#8211; <a href="https://www.youtube.com/@AritraSen">Aritra Sen &#8211; YouTube</a><br>Series link &#8211; <a href="https://youtube.com/playlist?list=PLOrU905yPYXIJrnREmOXHKnq2DhMwKdU7&amp;si=lSmnQYxcyDX6zLQE">https://youtube.com/playlist?list=PLOrU905yPYXIJrnREmOXHKnq2DhMwKdU7&amp;si=lSmnQYxcyDX6zLQE</a><br><br>Future series of playlists to come &#8211;<br><em>&#8211; Deep Learning with Pytorch<br>&#8211; NLP Zero to LLM<br>&#8211; Graph Neural Network</em><br><br><strong><span style="text-decoration: underline;">Subscribe the channel for more such contents.</span></strong><br><br>Thanks,<br>Aritra <br></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.aritrasen.com/announcement-launch-of-my-youtube-channel-focused-on-data-science/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Generative AI: LLMs: How to do LLM inference on CPU using Llama-2 1.9</title>
		<link>https://www.aritrasen.com/generative-ai-llms-how-to-do-llm-inference-on-cpu-using-llama-2-1-9/</link>
					<comments>https://www.aritrasen.com/generative-ai-llms-how-to-do-llm-inference-on-cpu-using-llama-2-1-9/#respond</comments>
		
		<dc:creator><![CDATA[Aritra Sen]]></dc:creator>
		<pubDate>Thu, 07 Sep 2023 11:45:58 +0000</pubDate>
				<category><![CDATA[Aritra Sen]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[deep-learning]]></category>
		<category><![CDATA[GenerativeAI]]></category>
		<category><![CDATA[LLM]]></category>
		<category><![CDATA[pytorch]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://www.aritrasen.com/?p=1042</guid>

					<description><![CDATA[In the last few posts, we talked about how to use Llama-2 model for performing different NLP tasks and for most of the cases I have used GPU in Kaggle kernels. Now there can be requirements to that you don&#8217;t have GPU and you need to build some apps using CPU only. In this short...]]></description>
										<content:encoded><![CDATA[
<p>In the last few posts, we talked about how to use Llama-2 model for performing different NLP tasks and for most of the cases I have used GPU in Kaggle kernels. Now there can be requirements to that you don&#8217;t have GPU and you need to build some apps using CPU only. In this short post we will see how we can use <strong>ctransformers </strong>library to load and do inference using LLama-2 in CPU only. <a href="https://github.com/marella/ctransformers">ctransformers</a> library are python bindings for the Transformer models implemented in C/C++ using&nbsp;<a href="https://github.com/ggerganov/ggml">GGML</a>&nbsp;library. Run the below command to install ctransformer library.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="264" height="118" src="https://www.aritrasen.com/wp-content/uploads/2023/09/image.png" alt="" class="wp-image-1043"/></figure></div>


<p>ctransformer library essentially helps to load the quantized models into CPU. With the ever-increasing size of LLMs, quantization plays a crucial role to use these giant models in community hardware efficiently with minimum compromise in the model performance. Recently, 8-bit and 4-bit quantization has helped us of&nbsp;running LLMs on consumer hardware. GGML (created by Georgi Gerganov , hence the name) was designed to be used with the llama.cpp library. The library is written in C/C++ for efficient inference of Llama models. It can load GGML models and run them on a CPU. To get the llama-2 7B GGML models for different quantization to this hugging-face link &#8211; <a href="https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/tree/main">TheBloke/Llama-2-7B-Chat-GGML at main (huggingface.co)</a></p>



<p>Based on the choice of quantization you can download the corresponding model file and place it in a local folder as shown below &#8211; </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="321" height="65" src="https://www.aritrasen.com/wp-content/uploads/2023/09/image-1.png" alt="" class="wp-image-1044" srcset="https://www.aritrasen.com/wp-content/uploads/2023/09/image-1.png 321w, https://www.aritrasen.com/wp-content/uploads/2023/09/image-1-300x61.png 300w" sizes="(max-width: 321px) 100vw, 321px" /></figure></div>


<p>As you can see, I have downloaded two different quantized models from the above given link 2bit and 4 bit quantized models.</p>



<p id="8211">They follow a particular naming convention: “q” + the number of bits used to store the weights (precision) + a particular variant. Here is a list of all the possible quant methods and their corresponding use cases, based on model cards made by TheBloke:</p>



<ul>
<li><code>q2_k</code>: Uses Q4_K for the attention.vw and feed_forward.w2 tensors, Q2_K for the other tensors.</li>



<li><code>q3_k_l</code>: Uses Q5_K for the attention.wv, attention.wo, and feed_forward.w2 tensors, else Q3_K</li>



<li><code>q3_k_m</code>: Uses Q4_K for the attention.wv, attention.wo, and feed_forward.w2 tensors, else Q3_K</li>



<li><code>q3_k_s</code>: Uses Q3_K for all tensors</li>



<li><code>q4_0</code>: Original quant method, 4-bit.</li>



<li><code>q4_1</code>: Higher accuracy than q4_0 but not as high as q5_0. However has quicker inference than q5 models.</li>



<li><code>q4_k_m</code>: Uses Q6_K for half of the attention.wv and feed_forward.w2 tensors, else Q4_K</li>



<li><code>q4_k_s</code>: Uses Q4_K for all tensors</li>



<li><code>q5_0</code>: Higher accuracy, higher resource usage and slower inference.</li>



<li><code>q5_1</code>: Even higher accuracy, resource usage and slower inference.</li>



<li><code>q5_k_m</code>: Uses Q6_K for half of the attention.wv and feed_forward.w2 tensors, else Q5_K</li>



<li><code>q5_k_s</code>: Uses Q5_K for all tensors</li>



<li><code>q6_k</code>: Uses Q8_K for all tensors</li>



<li><code>q8_0</code>: Almost indistinguishable from float16. High resource use and slow. Not recommended for most users.</li>
</ul>



<p>Once you download and place the model in your local file system, now you can easily load the model using below shown process and see how fast the model loads from disk &#8211;</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" fetchpriority="high" width="589" height="416" src="https://www.aritrasen.com/wp-content/uploads/2023/09/image-3.png" alt="" class="wp-image-1046" srcset="https://www.aritrasen.com/wp-content/uploads/2023/09/image-3.png 589w, https://www.aritrasen.com/wp-content/uploads/2023/09/image-3-300x212.png 300w" sizes="(max-width: 589px) 100vw, 589px" /></figure></div>


<p>Once loaded 4 bit llama-2 quantized model takes around 3.53 GB disk space. Similar way you can also load 13B Llama-2 models in your CPU also for inference from this link. &#8211; <a href="https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/tree/main">https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/tree/main</a></p>



<p>Using the 4bit quantized Llama-2 model and Gradio I have created the below shown demo using CPU only.</p>



<figure class="wp-block-embed aligncenter is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="LLM Demo" width="640" height="360" src="https://www.youtube.com/embed/gIbG8LhLirg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</div><figcaption class="wp-element-caption"><strong>Demo of LLM using Llama-2 and Gradio</strong></figcaption></figure>



<blockquote class="wp-block-quote">
<p>Do let me know in the comments if you like the video or not and in case you want me to create YouTube videos along with blogposts in future. Thanks for reading.</p>



<p>Reference: <a href="https://towardsdatascience.com/quantize-llama-models-with-ggml-and-llama-cpp-3612dfbcc172">Quantize Llama models with GGML and llama.cpp | Towards Data Science</a></p>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>https://www.aritrasen.com/generative-ai-llms-how-to-do-llm-inference-on-cpu-using-llama-2-1-9/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Generative AI: LLMs: Reduce Hallucinations with Retrieval-Augmented-Generation (RAG) 1.8</title>
		<link>https://www.aritrasen.com/generative-ai-llms-reduce-hallucinations-with-retrieval-augmented-generation-rag-1-8/</link>
					<comments>https://www.aritrasen.com/generative-ai-llms-reduce-hallucinations-with-retrieval-augmented-generation-rag-1-8/#respond</comments>
		
		<dc:creator><![CDATA[Aritra Sen]]></dc:creator>
		<pubDate>Sat, 26 Aug 2023 16:13:42 +0000</pubDate>
				<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[deep-learning]]></category>
		<category><![CDATA[GenerativeAI]]></category>
		<category><![CDATA[LLM]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://www.aritrasen.com/?p=1031</guid>

					<description><![CDATA[Though there is a huge hype and excitement about LLMs as they are really good at several NLP related tasks, however, they also come with few of the below mentioned issues: Frozen in time &#8211; LLMs are “frozen in time” and lack up-to-date information. This is due to the fact that these LLMs are trained with...]]></description>
										<content:encoded><![CDATA[
<p>Though there is a huge hype and excitement about LLMs as they are really good at several NLP related tasks, however, they also come with few of the below mentioned issues:</p>



<p><strong>Frozen in time</strong> &#8211; LLMs are “frozen in time” and lack up-to-date information. This is due to the fact that these LLMs are trained with a cutoff date and beyond that they are not aware anything, for the same reason if you can ask ChatGPT about Llama-2 they won&#8217;t be able to answer your questions with correct answers. These LLMs tends to hallucinate on these unknown questions and gives you a convincing wrong answer. </p>



<p><strong>Lack of domain-specific knowledge</strong>&nbsp;&#8211; LLMs are trained on open-sourced datasets for generalized tasks, meaning they do not know your or any company’s private data. So again, for domain specific questions they tend to give you again convincing wrong answers.</p>



<p>When a user sends above mentioned two types of questions to any LLM, they tend to hallucinate and give wrong answers as shown below due to the lack of context for the LLMs.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" loading="lazy" src="https://www.aritrasen.com/wp-content/uploads/2023/08/image-6.png" alt="" class="wp-image-1032" style="width:213px;height:541px" width="213" height="541" srcset="https://www.aritrasen.com/wp-content/uploads/2023/08/image-6.png 263w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-6-118x300.png 118w" sizes="(max-width: 213px) 100vw, 213px" /><figcaption class="wp-element-caption">LLM with Hallucination (Image: Author)</figcaption></figure></div>


<p>In the last <a href="https://www.aritrasen.com/generative-ai-llms-semantic-search-and-conversation-retrieval-using-vector-store-and-langchain-1-7/">blogpost</a> we talked about how we can split documents into chunks and then create embeddings. These embeddings can be stored in any Vector Store for future uses as shown below &#8211;<br><br></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="723" height="162" src="https://www.aritrasen.com/wp-content/uploads/2023/08/image-7.png" alt="" class="wp-image-1033" srcset="https://www.aritrasen.com/wp-content/uploads/2023/08/image-7.png 723w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-7-300x67.png 300w" sizes="(max-width: 723px) 100vw, 723px" /><figcaption class="wp-element-caption">Vector Store (Image: Author)</figcaption></figure></div>


<p>These documents can be anything like:<br>&#8211; Domain specific documents<br>&#8211; Documents / Knowledge base which are related to time frame after the training cut-off date of LLM.<br>&#8211; Company specific sensitive internal documents.<br>&#8211; etc.<br><em><strong>This type of Vector Stores can act as a knowledge base.</strong></em> </p>



<p><strong>Retrieval Augmented Generation</strong> (RAG) can help us to tackle the above-mentioned issues, RAG using the question embedding retrieves the nearest neighbor context from the Knowledge Base and adds the context to the query. Once the context is added to the query then the RAG sends the context aware query to the LLM for relevant answer. As now the model has the correct context to answer the query, the problem of hallucination can be reduced drastically. This process also much simpler than fine tuning or full finetuning process. The whole process is shown below- </p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" loading="lazy" src="https://www.aritrasen.com/wp-content/uploads/2023/08/image-8.png" alt="" class="wp-image-1035" style="width:621px;height:602px" width="621" height="602" srcset="https://www.aritrasen.com/wp-content/uploads/2023/08/image-8.png 728w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-8-300x291.png 300w" sizes="(max-width: 621px) 100vw, 621px" /><figcaption class="wp-element-caption">RAG (Image: Author)</figcaption></figure></div>


<p>New documents can be easily added back to the Knowledge Base so the problem of <em>&#8216;frozen in time&#8217;</em> can also be solved using the RAG methodology.<br>Example:</p>



<figure class="wp-block-image size-large"><img decoding="async" loading="lazy" width="1024" height="412" src="https://www.aritrasen.com/wp-content/uploads/2023/08/image-9-1024x412.png" alt="" class="wp-image-1037" srcset="https://www.aritrasen.com/wp-content/uploads/2023/08/image-9-1024x412.png 1024w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-9-300x121.png 300w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-9-768x309.png 768w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-9-850x342.png 850w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-9.png 1371w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p><br>Now let&#8217;s get our hands dirty with RAG with Llama-2.</p>



<p><script src="https://gist.github.com/aritrasen87/c574968feebb983cd32f2c9fb06cc75b.js"></script></p>



<p>Do like, share and comment if you have any questions or suggestions.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.aritrasen.com/generative-ai-llms-reduce-hallucinations-with-retrieval-augmented-generation-rag-1-8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Generative AI: LLMs: Semantic Search and Conversation Retrieval QA using Vector Store and LangChain 1.7</title>
		<link>https://www.aritrasen.com/generative-ai-llms-semantic-search-and-conversation-retrieval-using-vector-store-and-langchain-1-7/</link>
					<comments>https://www.aritrasen.com/generative-ai-llms-semantic-search-and-conversation-retrieval-using-vector-store-and-langchain-1-7/#comments</comments>
		
		<dc:creator><![CDATA[Aritra Sen]]></dc:creator>
		<pubDate>Fri, 25 Aug 2023 17:02:46 +0000</pubDate>
				<category><![CDATA[Aritra Sen]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[GenerativeAI]]></category>
		<category><![CDATA[LLM]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://www.aritrasen.com/?p=1021</guid>

					<description><![CDATA[In the last few blogposts, we have gone through the basics of LLMs and different fine-tuning approaches and basics of LangChain. In this post we will mainly work with the embeddings from LLM, how we can store these LLM embeddings in Vector Store and using this persistent vector db how we can do Semantic search....]]></description>
										<content:encoded><![CDATA[
<p>In the last few blogposts, we have gone through the basics of LLMs and different fine-tuning approaches and basics of LangChain. In this post we will mainly work with the embeddings from LLM, how we can store these LLM embeddings in Vector Store and using this persistent vector db how we can do Semantic search. Below are the high-level steps which we will do to perform the require operations &#8211;</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" loading="lazy" width="1024" height="462" src="https://www.aritrasen.com/wp-content/uploads/2023/08/image-5-1024x462.png" alt="" class="wp-image-1023" srcset="https://www.aritrasen.com/wp-content/uploads/2023/08/image-5-1024x462.png 1024w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-5-300x135.png 300w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-5-768x347.png 768w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-5-850x384.png 850w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-5.png 1316w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Semantic Search using Vector Store (Credit: Author)</figcaption></figure></div>


<p>Before going into the coding, let&#8217;s go through the steps in details- </p>



<ol>
<li><strong><span style="text-decoration: underline;">Loading Document:</span></strong><br>Using LangChain we can load different types of documents like pdf , csv , html etc. Follow this page to get more detailed understanding of the different document loaders &#8211;  <a href="https://python.langchain.com/docs/modules/data_connection/document_loaders/">https://python.langchain.com/docs/modules/data_connection/document_loaders/</a><br>For some of the document loaders like HTMLLoader and PDF Loader we need to install dependent libraires like BeautifulSoup, pypdf.<br></li>



<li><strong><span style="text-decoration: underline;">Transform Documents to Chunks:</span></strong><br>Once we load the document, we can access the document using page_content , however sometimes this page contents can be very large to be feed into the model (every LLM has a max input token limitations). So, we can create document chunks using below mentioned processes &#8211;<br>1. By using a chunk-size based on character length.<br>2. By using the size of input tokens.<br></li>



<li><strong><span style="text-decoration: underline;">Create Embeddings:</span></strong><br>Using LangChain we can create numeric embeddings of the text chunks. LangChain supports different LLM embeddings like OpenAI embedding, Sentence Transformer embedding etc.<br></li>



<li><strong><span style="text-decoration: underline;">Vector Store:</span></strong><br>Using Vector Store, we can store these document embeddings (persistent storage) for future uses like Semantic search. A user can send a search text and using LLM first we can convert that text to embeddings, using this query embedding and Vector Store embedding we can perform semantic search and retrieve the most relevant document/text using Vector Store. For this tutorial we will use the open-source vector store named chromadb (<a href="https://python.langchain.com/docs/modules/data_connection/vectorstores/">Vector stores | <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f99c.png" alt="🦜" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f517.png" alt="🔗" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Langchain</a>). Using vector store we can easily add, update, or delete new vectors.<br><br>Now let&#8217;s get our hands dirty.</li>
</ol>



<p><script src="https://gist.github.com/aritrasen87/09e5f8e590b937cf2a563b86f4057baf.js"></script></p>



<p>Do like, share and comment if you have any questions or suggestions.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.aritrasen.com/generative-ai-llms-semantic-search-and-conversation-retrieval-using-vector-store-and-langchain-1-7/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Generative AI: LLMs: LangChain + Llama-2-chat on Amazon mobile review dataset 1.6</title>
		<link>https://www.aritrasen.com/generative-ai-llms-langchain-llama-2-chat-on-amazon-mobile-review-dataset-1-6/</link>
					<comments>https://www.aritrasen.com/generative-ai-llms-langchain-llama-2-chat-on-amazon-mobile-review-dataset-1-6/#respond</comments>
		
		<dc:creator><![CDATA[Aritra Sen]]></dc:creator>
		<pubDate>Thu, 17 Aug 2023 09:09:36 +0000</pubDate>
				<category><![CDATA[Aritra Sen]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[deep-learning]]></category>
		<category><![CDATA[GenerativeAI]]></category>
		<category><![CDATA[LLM]]></category>
		<category><![CDATA[pytorch]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://www.aritrasen.com/?p=1000</guid>

					<description><![CDATA[In the last post we talked about in detail how we can fine tune a pretrained Llama-2 model using QLoRA. Llama-2 has two sets of models, first one was the model used in previous blogpost which is pretrained model then there is a instruction finetuned Llama-2 chat model which we will use in this post....]]></description>
										<content:encoded><![CDATA[
<p>In the last post we talked about in detail how we can fine tune a pretrained Llama-2 model using QLoRA. Llama-2 has two sets of models, first one was the model used in previous blogpost which is pretrained model then there is a instruction finetuned Llama-2 chat model which we will use in this post. <br>Llama-2 has been pretrained on an extensive corpus of self-supervised data, followed by alignment with human preferences via techniques such as Reinforcement Learning with Human Feedback (RLHF) to obtain the Llama-2 chat as shown in the below given image (Source: Llama2 paper)</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" loading="lazy" src="https://www.aritrasen.com/wp-content/uploads/2023/08/image.png" alt="" class="wp-image-1002" width="573" height="287" srcset="https://www.aritrasen.com/wp-content/uploads/2023/08/image.png 573w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-300x150.png 300w" sizes="(max-width: 573px) 100vw, 573px" /></figure></div>

<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="753" height="331" src="https://www.aritrasen.com/wp-content/uploads/2023/08/image-2.png" alt="" class="wp-image-1004" srcset="https://www.aritrasen.com/wp-content/uploads/2023/08/image-2.png 753w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-2-300x132.png 300w" sizes="(max-width: 753px) 100vw, 753px" /></figure></div>


<p>Prompt formats are kind of different in case of Llama-2 and Llama-2 as shown below-</p>



<figure class="wp-block-image size-large"><img decoding="async" loading="lazy" width="1024" height="248" src="https://www.aritrasen.com/wp-content/uploads/2023/08/image-3-1024x248.png" alt="" class="wp-image-1005" srcset="https://www.aritrasen.com/wp-content/uploads/2023/08/image-3-1024x248.png 1024w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-3-300x73.png 300w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-3-768x186.png 768w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-3-850x206.png 850w, https://www.aritrasen.com/wp-content/uploads/2023/08/image-3.png 1422w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong><span style="text-decoration: underline;">Langchain:</span></strong></p>



<p>LangChain gives us the building blocks to interface with any language model.</p>



<ul>
<li><a href="https://python.langchain.com/docs/modules/model_io/prompts/">Prompts</a>: Templatize, dynamically select, and manage model inputs</li>



<li><a href="https://python.langchain.com/docs/modules/model_io/models/">Language models</a>: Make calls to language models through common interfaces.</li>



<li><a href="https://python.langchain.com/docs/modules/model_io/output_parsers/">Output parsers</a>: Extract information from model outputs.<br></li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" loading="lazy" width="1024" height="393" src="https://www.aritrasen.com/wp-content/uploads/2023/08/Langchain-1024x393.jpg" alt="" class="wp-image-1007" srcset="https://www.aritrasen.com/wp-content/uploads/2023/08/Langchain-1024x393.jpg 1024w, https://www.aritrasen.com/wp-content/uploads/2023/08/Langchain-300x115.jpg 300w, https://www.aritrasen.com/wp-content/uploads/2023/08/Langchain-768x295.jpg 768w, https://www.aritrasen.com/wp-content/uploads/2023/08/Langchain-1536x590.jpg 1536w, https://www.aritrasen.com/wp-content/uploads/2023/08/Langchain-2048x786.jpg 2048w, https://www.aritrasen.com/wp-content/uploads/2023/08/Langchain-850x326.jpg 850w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Langchain flow (Source: <a href="https://python.langchain.com/docs/modules/model_io/">Model I/O | <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f99c.png" alt="🦜" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f517.png" alt="🔗" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Langchain</a>)</figcaption></figure></div>


<p>In the below notebook, we will try out Llama-2-chat model and will explore the benefits of using Langchain as a platform to several LLM tasks like </p>



<ol>
<li>Text summarization</li>



<li>Sentiment Analysis</li>



<li>Topic extraction</li>



<li>Battery issues identification from mobile review.</li>
</ol>



<p><script src="https://gist.github.com/aritrasen87/addcb02296a1d8f97ae48e52f2519a1e.js"></script></p>



<p>Do like, share and comment if you have any questions or suggestions.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.aritrasen.com/generative-ai-llms-langchain-llama-2-chat-on-amazon-mobile-review-dataset-1-6/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Generative AI: LLMs: Finetuning Llama2 with QLoRA on custom dataset 1.5</title>
		<link>https://www.aritrasen.com/generative-ai-llms-finetuning-llama2-with-qlora-on-custom-dataset/</link>
					<comments>https://www.aritrasen.com/generative-ai-llms-finetuning-llama2-with-qlora-on-custom-dataset/#respond</comments>
		
		<dc:creator><![CDATA[Aritra Sen]]></dc:creator>
		<pubDate>Thu, 27 Jul 2023 14:47:12 +0000</pubDate>
				<category><![CDATA[Aritra Sen]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[deep-learning]]></category>
		<category><![CDATA[GenerativeAI]]></category>
		<category><![CDATA[LLM]]></category>
		<category><![CDATA[pytorch]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">http://www.aritrasen.com/?p=985</guid>

					<description><![CDATA[In the last post in this series, we have gone through the inner workings of LoRA fine tuning process. In this blogpost we will use the concepts of LoRA with the quantization method. We will use the newly launched Llama2 which is one of the biggest LLM launch in the history of open-source models. Below...]]></description>
										<content:encoded><![CDATA[
<p>In the last post in this series, we have gone through the inner workings of LoRA fine tuning process. In this blogpost we will use the concepts of LoRA with the quantization method. We will use the newly launched Llama2 which is one of the biggest LLM launch in the history of open-source models. Below are the steps to be used in the below given notebooks and details about each process:</p>



<ol>
<li>Install required packages.</li>



<li>Prepare the dataset for instruction fine-tuning.</li>



<li>Define quantization_config using BitsAndBytes.</li>



<li>Load the Llama-2 shared model with quantization_config.</li>



<li>Create the Llama-2 tokenizer.</li>



<li>create the peft_config to finetune the LoRA for q,v attention metrices.</li>



<li>Define the training arguments.</li>



<li>create the trainer with SFTTrainer.</li>



<li>train the model.</li>



<li>Inference phase.</li>
</ol>



<p>Before start coding the whole process, let&#8217;s understand few of concepts which we are yet to go through in this blog post series-</p>



<p><strong><span style="text-decoration: underline;">Data Preparation:</span></strong><br>In this post we will use the dialogsum from hugging face dataset module. Dataset has 4 features which is divided in the train, test and validation dataset. Features are &#8211; [&#8216;id&#8217;, &#8216;dialogue&#8217;, &#8216;summary&#8217;, &#8216;topic&#8217;]. Our interest of features are dialogue and summary. Basic we trying to fine tune our model for a text summarization task using this dataset. We will prepare the dataset in such a way that it will be used for instruction finetuning. Instruction fine-tuning&nbsp;uses a set of labeled examples in the form of {prompt,instruction,input,output} pairs to further train the pre-trained model in for a particular task. Below function is self-explanatory for the data preparation step.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" loading="lazy" src="https://www.aritrasen.com/wp-content/uploads/2023/07/image-1-1024x388.png" alt="" class="wp-image-986" width="697" height="264" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/image-1-1024x388.png 1024w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-1-300x114.png 300w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-1-768x291.png 768w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-1-850x322.png 850w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-1.png 1358w" sizes="(max-width: 697px) 100vw, 697px" /><figcaption class="wp-element-caption">Preparation instruction-based dataset (Credit: Author)</figcaption></figure></div>


<p><strong><span style="text-decoration: underline;">Quantization:</span></strong><br>With the rapid development of LLM, its feels like every other day we are getting new LLMs with are indeed very large with lot of parameters. Most challenging aspect is to fit these models with minimum hardware requirements like a single GPU. For example, to fine-tune BLOOM-176B, you&#8217;d need 72 GPUs (8x 80GB A100 GPUs). Lot of research is going to find ways to fit these models in easily accessible Hardwares. One such way is Quantization. To understand this process let&#8217;s first understand the data types which are being used and how they are represented. Size of any model would highly be deepened on the number of parameters and the precision (float32, float16 or bfloat16) of these parameters. Idea is to reduce the model size using lower precision without affecting the model performance as shown below-<br></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="660" height="421" src="https://www.aritrasen.com/wp-content/uploads/2023/07/tf32-Mantissa-chart-hi-res-FINAL.png" alt="" class="wp-image-987" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/tf32-Mantissa-chart-hi-res-FINAL.png 660w, https://www.aritrasen.com/wp-content/uploads/2023/07/tf32-Mantissa-chart-hi-res-FINAL-300x191.png 300w" sizes="(max-width: 660px) 100vw, 660px" /><figcaption class="wp-element-caption">Credit: https://blogs.nvidia.com/blog/2020/05/14/tensorfloat-32-precision-format/</figcaption></figure></div>


<ul>
<li>FP32: 8 bits are reserved for the &#8220;exponent&#8221;, 23 bits for the &#8220;mantissa&#8221; and 1 bit for the &#8220;sign&#8221; of the number. With this datatype huge range of numbers can be represented.</li>



<li>FP16: 5 bits are reserved for the exponent and 10 bits are reserved for the mantissa. Due to reduction of precision lesser range of numbers can be represented. This exposes FP16 numbers<br>to the risk of overflowing (trying to represent a number that is very large) and underflowing (representing a number that is very small).</li>



<li>BF16: To tackle the problem of FP16 , BF16 has been introduced where 8 bits are reserved for the exponent (which is the same as FP32) and 7 bits are reserved for the fraction.</li>
</ul>



<p>I hope you got an idea that using Quantization we can reduce the size of the model. There are techniques of quantization also , for more details please refer to this wonderfully written hugging face blog &#8211; https://huggingface.co/blog/4bit-transformers-bitsandbytes .We will use the bitsandbytes library to load the Llama-2 model with quantization parameters.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="344" height="141" src="https://www.aritrasen.com/wp-content/uploads/2023/07/image-3.png" alt="" class="wp-image-990" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/image-3.png 344w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-3-300x123.png 300w" sizes="(max-width: 344px) 100vw, 344px" /><figcaption class="wp-element-caption">Quantization Config (Credit: Author)</figcaption></figure></div>


<p><strong><span style="text-decoration: underline;">Llama-2:</span></strong><br>Abstract from the Llama-2 paper by Meta:</p>



<p><em>In this work, we develop and release Llama 2, a collection of pretrained and fine-tuned large language models (LLMs) ranging in scale from 7 billion to 70 billion parameters. Our fine-tuned LLMs, called Llama 2-Chat, are optimized for dialogue use cases. Our models outperform open-source chat models on most benchmarks we tested,and based on our human evaluations for helpfulness and safety, may be a suitable substitute for closed-source models. We provide a detailed description of our approach to fine-tuning and safety improvements of Llama 2-Chat in order to enable the community to build on our work and contribute to the responsible development of LLMs.</em><br>Get the details of the all the models available: <a href="https://huggingface.co/models?search=llama2">Models &#8211; Hugging Face</a></p>



<p><strong><span style="text-decoration: underline;">Sharded Model:</span></strong><br>Sharded model is helpful for distributed training of large pretrained models like LLMs. It is achieved by sharding the model parameters, gradients, and optimizer states across data parallel processes, and it can also offload sharded model parameters to a CPU. In this coding exercise we have used the shared model version of Llama-2 to work in a single GPU. You can see that 14 shards has been downloaded which initializing the model for the first time.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" loading="lazy" src="https://www.aritrasen.com/wp-content/uploads/2023/07/Sharded_Model_Llama-2-1024x621.png" alt="" class="wp-image-988" width="616" height="373" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/Sharded_Model_Llama-2-1024x621.png 1024w, https://www.aritrasen.com/wp-content/uploads/2023/07/Sharded_Model_Llama-2-300x182.png 300w, https://www.aritrasen.com/wp-content/uploads/2023/07/Sharded_Model_Llama-2-768x466.png 768w, https://www.aritrasen.com/wp-content/uploads/2023/07/Sharded_Model_Llama-2-850x516.png 850w, https://www.aritrasen.com/wp-content/uploads/2023/07/Sharded_Model_Llama-2.png 1152w" sizes="(max-width: 616px) 100vw, 616px" /><figcaption class="wp-element-caption">Sharded Llama-2 model (Credit: Author)</figcaption></figure></div>


<p><strong><span style="text-decoration: underline;">Peft config:</span></strong><br>In the last blog post we discussed in detail that in LoRA we train task specific low rank adopters which are generally q,v metrices of attention layers and keep the everything of the pretrained model weights freezed. Using the peft library we will create new low rank adopters for q_proj and v_proj as shown below with given rank (r=8).</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" loading="lazy" src="https://www.aritrasen.com/wp-content/uploads/2023/07/image-2.png" alt="" class="wp-image-989" width="290" height="255" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/image-2.png 388w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-2-300x264.png 300w" sizes="(max-width: 290px) 100vw, 290px" /><figcaption class="wp-element-caption">Configuring LoRA(Credit: Author)</figcaption></figure></div>


<p><strong><span style="text-decoration: underline;">Training Arguments:</span></strong><br>Using <a rel="noreferrer noopener" href="https://huggingface.co/docs/trl/main/en/sft_trainer" target="_blank">Supervised Fine-tuning Trainer (huggingface.co)</a> (SFTTrainer) we are finetuning the Llama-2 model on out custom dataset. To keep the article short please refer for training arguments details &#8211; <a href="https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments">Trainer (huggingface.co)</a></p>



<p><strong><span style="text-decoration: underline;">Inference using QLoRA Adopters:</span></strong><br>Once the adapter is trained you can pass the saved model in the get_peft_model function along with the original model to get the new LoRA finetuned model.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" loading="lazy" width="1024" height="228" src="https://www.aritrasen.com/wp-content/uploads/2023/07/image-4-1024x228.png" alt="" class="wp-image-993" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/image-4-1024x228.png 1024w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-4-300x67.png 300w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-4-768x171.png 768w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-4-850x190.png 850w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-4.png 1255w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Llama2 + QLoRA = Finetuned model (Credit: Author)</figcaption></figure></div>


<p>You can get an idea of the whole process how to fine-tune a Llama-2 model using QLoRA. I have run the model in Kaggle kernel with 1 GPU and whole process is working fine. I will work further refining the process to improve the QLoRA outputs.<br><span style="text-decoration: underline;">Update: Code changes has been done to fix the repeating text output. Now the text summarization is working properly.</span></p>



<p><script src="https://gist.github.com/aritrasen87/48c9da7dd535e35c7146f7fbf75a486d.js"></script></p>



<p>Do like, share and comment if you have any questions or suggestions.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.aritrasen.com/generative-ai-llms-finetuning-llama2-with-qlora-on-custom-dataset/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Generative AI: LLMs: LoRA fine tuning 1.4</title>
		<link>https://www.aritrasen.com/generative-ai-llms-lora-fine-tuning-1-4/</link>
					<comments>https://www.aritrasen.com/generative-ai-llms-lora-fine-tuning-1-4/#respond</comments>
		
		<dc:creator><![CDATA[Aritra Sen]]></dc:creator>
		<pubDate>Wed, 19 Jul 2023 13:42:29 +0000</pubDate>
				<category><![CDATA[Aritra Sen]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[deep-learning]]></category>
		<category><![CDATA[LLM]]></category>
		<category><![CDATA[LoRA]]></category>
		<category><![CDATA[pytorch]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">http://www.aritrasen.com/?p=970</guid>

					<description><![CDATA[In the last post we discussed two approaches to fine tuning using feature-based method, these options may not be always efficient in terms of computational complexity as well as time complexity. Full fine tuning of any LLM models needs to stitch the below mentioned steps together: Combination of all these steps can produce lot of...]]></description>
										<content:encoded><![CDATA[
<p>In the last post we discussed two approaches to fine tuning using feature-based method, these options may not be always efficient in terms of computational complexity as well as time complexity. Full fine tuning of any LLM models needs to stitch the below mentioned steps together:</p>



<ol>
<li>Load dataset in memory</li>



<li>Load pretrained model in the memory</li>



<li>Foward pass through the network</li>



<li>Loss calculation and gradient calculations</li>



<li>Optimize the weights</li>
</ol>



<p>Combination of all these steps can produce lot of challenges in terms of &#8211;</p>



<ol>
<li>Memory requirements</li>



<li>Computational requirements like more GPU</li>



<li>Training time and associated cost</li>



<li>Inference time</li>
</ol>



<p>In one of the <a rel="noreferrer noopener" href="https://arxiv.org/pdf/2106.09685.pdf" target="_blank">paper</a> published by Microsoft, it has been shown that there exists a way called Parameter Efficient fine tuning which can help to tackle the above-mentioned problems. In this paper a technique called <em>LoRA (Low Rank Adoption)</em> has been introduced. In principle the concept resolves around the concept of Matrix Decomposition in lower ranks. A full fine-tuning of LLM goes through mainly two separate steps to generate the embeddings &#8211; 1. Foward pass through the network 2. Weights updates and in the end get the final embeddings as shown below &#8211;</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="374" height="436" src="https://www.aritrasen.com/wp-content/uploads/2023/07/Weight_Updates.jpg" alt="" class="wp-image-971" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/Weight_Updates.jpg 374w, https://www.aritrasen.com/wp-content/uploads/2023/07/Weight_Updates-257x300.jpg 257w, https://www.aritrasen.com/wp-content/uploads/2023/07/Weight_Updates-300x350.jpg 300w" sizes="(max-width: 374px) 100vw, 374px" /><figcaption class="wp-element-caption"><span style="text-decoration: underline;"><strong>Full finetuning of LLMs (Image: Author)</strong></span></figcaption></figure></div>


<p>In case of LoRA it has been shown that pretrained model has low intrinsic dimensions, in other words there exists a low dimension reparameterization that is as effective doing the full parameter fine tuning. Pretrained weights can decomposed in low rank (Rank is linearly independently rows or columns of a matrix) matrices as shown below-</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="685" height="342" src="https://www.aritrasen.com/wp-content/uploads/2023/07/Low-Rank-Matrix-Decomposition-1.jpg" alt="" class="wp-image-973" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/Low-Rank-Matrix-Decomposition-1.jpg 685w, https://www.aritrasen.com/wp-content/uploads/2023/07/Low-Rank-Matrix-Decomposition-1-300x150.jpg 300w" sizes="(max-width: 685px) 100vw, 685px" /><figcaption class="wp-element-caption"><span style="text-decoration: underline;"><strong>Low Rank representation (Image: Author)</strong></span></figcaption></figure></div>


<p>For examples imagine that W is the pre trained weights with the dimension of 512 X 64. So we can say that if we want to full finetune the weights that total number of parameters would be 512 X 64 = 32768 which is lot of parameters to train. However, if we use two low rank matrices where the rank is 4 then these two matrices A and B can be represented (low dimension reparameterization) as follows </p>



<p>&#8211; A &#8211; 4 X 64 and B &#8211; 512 X 4.</p>



<p>So the total numbers of parameters would be (4 x 64 + 512 x 4) = 2304 which lot less when we compared to approximately 32k parameters. During training time, we freeze the pre-trained model parameters frozen and only train these two low rank matrices. During inference we combine these two matrices and add back to the pre-trained model weights as shown below &#8211;</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="600" height="439" src="https://www.aritrasen.com/wp-content/uploads/2023/07/lora-animated.gif" alt="" class="wp-image-975"/><figcaption class="wp-element-caption"><strong><span style="text-decoration: underline;">LoRA (Image: Huggingface)</span></strong></figcaption></figure></div>


<p>We can also train these low rank metrices for specific tasks and during inference time we can add back the task specific LoRA weights to the pretrained weights as shown below &#8211;</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="921" height="316" src="https://www.aritrasen.com/wp-content/uploads/2023/07/TaskSpecificLORA.jpg" alt="" class="wp-image-976" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/TaskSpecificLORA.jpg 921w, https://www.aritrasen.com/wp-content/uploads/2023/07/TaskSpecificLORA-300x103.jpg 300w, https://www.aritrasen.com/wp-content/uploads/2023/07/TaskSpecificLORA-768x264.jpg 768w, https://www.aritrasen.com/wp-content/uploads/2023/07/TaskSpecificLORA-850x292.jpg 850w" sizes="(max-width: 921px) 100vw, 921px" /><figcaption class="wp-element-caption"><strong><span style="text-decoration: underline;">Task Specific LoRA (Image: Author)</span></strong></figcaption></figure></div>


<p>In the previously mentioned paper it has been shown that similar model performence like full fine tuning can be achieved with LoRA as shown below &#8211;</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="479" height="214" src="https://www.aritrasen.com/wp-content/uploads/2023/07/LoRA_Performence.jpg" alt="" class="wp-image-977" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/LoRA_Performence.jpg 479w, https://www.aritrasen.com/wp-content/uploads/2023/07/LoRA_Performence-300x134.jpg 300w" sizes="(max-width: 479px) 100vw, 479px" /><figcaption class="wp-element-caption"><strong><span style="text-decoration: underline;">LoRA performance comparison (Image: LoRA Paper)</span></strong></figcaption></figure></div>


<p> In the LoRA they used the low rank adoption for different attention weight matrices like Q ,V. The study in the paper has been limited to only adapting the attention weights for downstream tasks and freeze the MLP modules (so they are not trained in downstream tasks) both for simplicity and parameter-efficiency. Surprisingly it has been observed that with low rank as low as r=1 very good performance can be achieved (r is hyperparameter to tune).</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" loading="lazy" src="https://www.aritrasen.com/wp-content/uploads/2023/07/image-1024x293.png" alt="" class="wp-image-978" width="739" height="211" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/image-1024x293.png 1024w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-300x86.png 300w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-768x220.png 768w, https://www.aritrasen.com/wp-content/uploads/2023/07/image-850x243.png 850w, https://www.aritrasen.com/wp-content/uploads/2023/07/image.png 1049w" sizes="(max-width: 739px) 100vw, 739px" /><figcaption class="wp-element-caption"><strong><span style="text-decoration: underline;">How to chose the rank ? (Image: LoRA paper)</span></strong></figcaption></figure></div>


<p>In the next blog post we will implement the LoRA in code. Do like, share the post in case you find this post useful. Thanks for reading.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.aritrasen.com/generative-ai-llms-lora-fine-tuning-1-4/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Generative AI: LLMs: Feature base finetuning 1.3</title>
		<link>https://www.aritrasen.com/generative-ai-llms-feature-base-finetuning-1-3/</link>
					<comments>https://www.aritrasen.com/generative-ai-llms-feature-base-finetuning-1-3/#respond</comments>
		
		<dc:creator><![CDATA[Aritra Sen]]></dc:creator>
		<pubDate>Wed, 12 Jul 2023 07:27:35 +0000</pubDate>
				<category><![CDATA[Aritra Sen]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[deep-learning]]></category>
		<category><![CDATA[Finetuning]]></category>
		<category><![CDATA[LLM]]></category>
		<category><![CDATA[transformers]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">http://www.aritrasen.com/?p=959</guid>

					<description><![CDATA[In the last post we talked about how to do In-context finetuning using few shot techniques, In-context finetuning works when we don&#8217;t have much data, or we don&#8217;t have access to the full model. This technique has certain limitations like the more examples you add in the prompt the context length increases a lot and...]]></description>
										<content:encoded><![CDATA[
<p>In the last post we talked about how to do In-context finetuning using few shot techniques, In-context finetuning works when we don&#8217;t have much data, or we don&#8217;t have access to the full model. This technique has certain limitations like the more examples you add in the prompt the context length increases a lot and there is always cut off on how much benefit you can get out in-context fine tuning. </p>



<p>Here comes the technique of the feature based fine tuning when we have lot of data to fine-tune LLM and we have full access to the LLM for doing any downstream task like Classification, Sentiment analysis etc. In general feature based fine tuning can be done using the below mentioned two approaches, I already have written two blog posts on these two approaches, I am attached the link of these tutorials here:</p>



<ol>
<li><strong>Update the weights of the pre-trained LLM model along with the classification layer.</strong><br>In practice, finetuning all layers almost always results in superior performance; however, this process is a resource intensive and time-consuming process. Hardware requirements like GPU is almost essential.</li>
</ol>



<figure class="wp-block-embed is-type-wp-embed is-provider-denken wp-block-embed-denken"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="BPswx1VaTb"><a href="https://www.aritrasen.com/1-1-fine-tune-a-transformer-model-1-2/">1.1 &#8211; Fine Tune a Transformer Model (1/2)</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted" title="&#8220;1.1 &#8211; Fine Tune a Transformer Model (1/2)&#8221; &#8212; Denken" src="https://www.aritrasen.com/1-1-fine-tune-a-transformer-model-1-2/embed/#?secret=ShfmIiQtVK#?secret=BPswx1VaTb" data-secret="BPswx1VaTb" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div><figcaption class="wp-element-caption"><strong><span style="text-decoration: underline;">Code Example of Approach 1</span></strong></figcaption></figure>



<p><strong>2. Update only the weights of the classification layer and not the pre-trained LLM model. </strong><br>This process acts as using the pre-trained LLM model for feature extraction. This approach is much more efficient in terms of resource consumption and time required. Different heads can be trained for different downstream tasks using this approach.</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-denken wp-block-embed-denken"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="kDEVeinGWB"><a href="https://www.aritrasen.com/1-2-fine-tune-a-transformer-model-2-2/">1.2 – Fine Tune a Transformer Model (2/2)</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted" title="&#8220;1.2 – Fine Tune a Transformer Model (2/2)&#8221; &#8212; Denken" src="https://www.aritrasen.com/1-2-fine-tune-a-transformer-model-2-2/embed/#?secret=gpTkuQ3Ku7#?secret=kDEVeinGWB" data-secret="kDEVeinGWB" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div><figcaption class="wp-element-caption"><strong><span style="text-decoration: underline;">Code Example of Approach 2</span></strong></figcaption></figure>



<figure class="wp-block-image size-full is-resized"><img decoding="async" loading="lazy" src="https://www.aritrasen.com/wp-content/uploads/2023/07/Feature_Based_finetuning.jpg" alt="" class="wp-image-966" width="756" height="541" title="Feature based finetuning of LLMs" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/Feature_Based_finetuning.jpg 756w, https://www.aritrasen.com/wp-content/uploads/2023/07/Feature_Based_finetuning-300x215.jpg 300w" sizes="(max-width: 756px) 100vw, 756px" /><figcaption class="wp-element-caption"><strong>Feature based finetuning of LLMs (Performence vs Training time) (Source : <a href="https://substack.com/@rasbt">SEBASTIAN RASCHKA, PHD</a>)</strong></figcaption></figure>



<p>From the above image we can see that feature based finetuning requires more training time to get optimal model performance and these processes are always not resource efficient finetuning approaches.<br>More fine-tuning approaches to come in this blog post series.</p>



<p>Do like, share and comment if you have any questions.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.aritrasen.com/generative-ai-llms-feature-base-finetuning-1-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Generative AI: LLMs: In Context Learning 1.2</title>
		<link>https://www.aritrasen.com/generative-ai-llms-in-context-learning-1-2/</link>
					<comments>https://www.aritrasen.com/generative-ai-llms-in-context-learning-1-2/#respond</comments>
		
		<dc:creator><![CDATA[Aritra Sen]]></dc:creator>
		<pubDate>Mon, 10 Jul 2023 14:16:28 +0000</pubDate>
				<category><![CDATA[Aritra Sen]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Finetuning]]></category>
		<category><![CDATA[LLMs]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">http://www.aritrasen.com/?p=945</guid>

					<description><![CDATA[From this blog post onwards, we will talk about different fine-tuning approaches for LLMs. As discussed in the last last post In context learning helps in below mentioned two situations: 1. We don&#8217;t have access to the full model. We only have access to the API of the model.2. When we don&#8217;t have much data...]]></description>
										<content:encoded><![CDATA[
<p>From this blog post onwards, we will talk about different fine-tuning approaches for LLMs. As discussed in the last last post In context learning helps in below mentioned two situations: <br>1. We don&#8217;t have access to the full model. We only have access to the API of the model.<br>2. When we don&#8217;t have much data to train any model.<br>Using OpenAI API key below I tried to show how we can do in context learning.</p>



<p><script src="https://gist.github.com/aritrasen87/05fcbf4b1f86a67515748f274228fa03.js"></script></p>



<p>Few of the limitation of in context learning is that the more examples we add in the prompt the context length increases with number of examples which is not an efficient fine-tuning approach. If we lot of data better approach to fine tuning with instruction in given in the <a href="https://platform.openai.com/docs/guides/fine-tuning" target="_blank" rel="noreferrer noopener">OpenAI documentation</a>.</p>



<p>Do like, share and comment if you have any questions.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.aritrasen.com/generative-ai-llms-in-context-learning-1-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Generative AI: LLMs: Finetuning Approaches 1.1</title>
		<link>https://www.aritrasen.com/generative-ai-llms-finetuning-approaches-1-1/</link>
					<comments>https://www.aritrasen.com/generative-ai-llms-finetuning-approaches-1-1/#respond</comments>
		
		<dc:creator><![CDATA[Aritra Sen]]></dc:creator>
		<pubDate>Thu, 06 Jul 2023 15:00:00 +0000</pubDate>
				<category><![CDATA[Aritra Sen]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[deep-learning]]></category>
		<category><![CDATA[Finetuning]]></category>
		<category><![CDATA[GenerativeAI]]></category>
		<category><![CDATA[LLM]]></category>
		<category><![CDATA[pytorch]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">http://www.aritrasen.com/?p=934</guid>

					<description><![CDATA[In the last post in this Generative AI with LLMs series we talked about different types of LLM model and how they are generally pre-trained. These Deep Learning language models with large numbers of parameters are generally trained on open-sourced data like Common Crawl, The Pile, MassiveText, blogs, Wikipedia, GitHub etc. These datasets are generally...]]></description>
										<content:encoded><![CDATA[
<p>In the last post in this Generative AI with LLMs series we talked about different types of LLM model and how they are generally pre-trained. These Deep Learning language models with large numbers of parameters are generally trained on open-sourced data like Common Crawl, The Pile, MassiveText, blogs, Wikipedia, GitHub etc. These datasets are generally from different domains and different topics which are generic in nature. However, these LLMs may not perform as well on specific task in hand without finetuning. For example, if you want to use a pretrained LLM for NLP tasks or bio-medical documents/texts, finetuning (or in context learning) it on a corpus of bio-medical documents can significantly improve the model&#8217;s performance.<br><br>This blog posts will try to show and discuss different available approaches to do the finetuning for a task in hand. We will discuss each of the topics briefly in this post and in future post we go in depth to the topics in detail with code. <br><img decoding="async" loading="lazy" width="1281" height="336" class="wp-image-939" style="width: 1100px;" src="https://www.aritrasen.com/wp-content/uploads/2023/07/Finetuning_Roadmap-2.jpg" alt="" srcset="https://www.aritrasen.com/wp-content/uploads/2023/07/Finetuning_Roadmap-2.jpg 1281w, https://www.aritrasen.com/wp-content/uploads/2023/07/Finetuning_Roadmap-2-300x79.jpg 300w, https://www.aritrasen.com/wp-content/uploads/2023/07/Finetuning_Roadmap-2-1024x269.jpg 1024w, https://www.aritrasen.com/wp-content/uploads/2023/07/Finetuning_Roadmap-2-768x201.jpg 768w" sizes="(max-width: 1281px) 100vw, 1281px" /><br><br>Let&#8217;s get started with brief discussion on each of the above shown approaches: <br><br><strong><span style="text-decoration: underline;">In context learning:</span></strong><br>In context learning is way to go when we don&#8217;t have access to the full LLM and we are using an API to access the LLM for example when we are using OpenAI gpt-35-turbo model to make API calls. We have seen that with the recent development of GPT 3/ Chat GPT we can do zero shot prompting or few-shot prompting to get better results when we use these models for a task in hand. In few shot prompting we provide one or multiple examples of the task embedded in the input prompt to the model. In the next blog post tutorial, we will go through we can do it in python.</p>



<p><strong><span style="text-decoration: underline;">Feature based finetuning:</span></strong><br>In feature based finetuning we should have access to the full LLM model like BERT which can be finetuned in generally two of the approaches to get much better performance on domain specific downstream task like sentiment classification. In Feature base finetuning we can attach a new classification or task specific head and the newly added task specific head can be trained or we can also tune all the layers of LLM along with the newly added head. More in depth discussion to be done in the future blog posts.</p>



<p><strong><span style="text-decoration: underline;">Quantization (Model run time/space optimization):</span></strong></p>



<p>Quantization is generally a model optimization technique. In the feature base finetuning we generally play with the number of params to fine tune, Quantization takes a different approach where we try to represent the weights, biases and gradients of the LLMs with low precision data types like 8-bit integer (INT8) instead of the usual 32-bit floating point (FP32). By reducing the number of bits, we can reduce the size of the model to be finetuned, which in turn can help in the finetuning process by reducing the memory and run time.</p>



<p><strong><span style="text-decoration: underline;">Multitask instruction finetuning:</span></strong></p>



<p>So far, all the above methods mentioned above talks about finetuning the whole LLM for a single downstream task. Tuning the model for a single downstream task can lead to the phenomenon named <strong>&#8216;Catastrophic forgetting&#8217;</strong> where learns to do the task for which it was finetuned however it performs very poorly on the other tasks. For example, a LLM finetuned for sentiment classification can start performing very poorly on other tasks like text summarization, named entity recognition. To avoid catastrophic forgetting we can fine tune the model on mixture of instruction prompts. FLAN group of models like <a href="https://huggingface.co/docs/transformers/model_doc/flan-t5" data-type="URL" data-id="https://huggingface.co/docs/transformers/model_doc/flan-t5" target="_blank" rel="noreferrer noopener">FLAN-T5</a> is one such model.</p>



<p><strong><span style="text-decoration: underline;">Parameter Efficient Fine Tuning (PEFT):</span></strong><br>PEFT reuses the pre-trained model with minimum new params to be trained using the fine-tuning process. Go for PEFT when you want to optimize the below mentioned criteria:</p>



<ol>
<li>computational costs and hardware (requires fewer GPUs and GPU time)</li>



<li>Minimum training time</li>



<li>Better modeling performance by reducing overfitting)</li>



<li>Requires less storage as newly added or trained params are very minimum in size.</li>
</ol>



<p>On a high level we can categorize the PEFT in below mentioned approaches, which we would discuss in detail in with code implementation in future blog posts.</p>



<ol>
<li><span style="text-decoration: underline;"><em>LoRA (reparameterization):</em></span><br>In Low Rank Adaption LLM fine tuning new two low rank metrices (using matrix decomposition) gets introduced to the fine-tuning process keeping the pre-trained model weights unchanged. These low rank metrices can be specific to different tasks. During inference time these task specific low rank metrices can be added back to the pre-trained model weights to get better performance on individual tasks.</li>
</ol>



<p>    <span style="text-decoration: underline;"><em>2. Adapters:</em></span><br>According to research a BERT model trained with the adapter method reaches a similar modeling performance comparable to a fully finetuned BERT model while only requiring the training of 3.6% of the parameters. This method adds additional parameters/layers to each transformer block and trains only these additional parameters keeping original parameters frozen.</p>



<p>    <span style="text-decoration: underline;"><em>3. Soft prompt tuning:</em></span><br>Soft prompt tuning is different than traditional prompt tuning, in soft prompt tuning or prefix tuning prepends tunable tensors to the embeddings on the input.</p>



<p><strong><span style="text-decoration: underline;">Reinforcement Learning with Human feedback (RLHF):</span></strong><br>In this process we include human feedback in the loop of fine tuning. In this process at first step is to generate human labelled dataset where human rank the LLM outputs based on certain criteria like toxicity/relevance/quality of output. Using this labelled dataset, a reward model in trained which gives reward to the outputs generated by LLM. Based on the reward a RL algorithm (proximal policy update) fine tunes the weights of the LLMs. This technique is one of the main reasons behind the success of ChatGPT.</p>



<p>In the future blog post we will try to get into depth of these techniques.</p>



<p>Thanks for your time, hope you have enjoyed reading, do share if you like the post.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.aritrasen.com/generative-ai-llms-finetuning-approaches-1-1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
