<?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 Maanjunath S Naragund on Medium]]></title>
        <description><![CDATA[Stories by Maanjunath S Naragund on Medium]]></description>
        <link>https://medium.com/@maanjunathn07ds?source=rss-fa05ca8ae5a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9E2PJrwFyGVq6dcz2gmShg.jpeg</url>
            <title>Stories by Maanjunath S Naragund on Medium</title>
            <link>https://medium.com/@maanjunathn07ds?source=rss-fa05ca8ae5a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:15:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maanjunathn07ds/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[Understanding Value Functions, Bellman Equation, and Learning in Reinforcement Learning]]></title>
            <link>https://blog.gopenai.com/understanding-value-functions-bellman-equation-and-learning-in-reinforcement-learning-03974452acef?source=rss-fa05ca8ae5a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/03974452acef</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Maanjunath S Naragund]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 08:02:58 GMT</pubDate>
            <atom:updated>2026-06-23T07:42:00.417Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the previous blog, <a href="https://medium.com/gopenai/reinforcement-learning-learning-through-trial-and-error-353559520b14"><strong>“Reinforcement Learning: Learning Through Trial and Error”</strong></a>, we introduced the fundamentals of Reinforcement Learning (RL). We explored the RL framework, state vs observation, different types of RL tasks, the exploration-exploitation trade-off, and the role of Deep Learning in Reinforcement Learning.</p><p>If you have not read Part 1, I recommend starting there before continuing with this article, as it introduces the core concepts and terminology that will be used throughout this blog.</p><p>In this article, we will go one step deeper.</p><p>One important question remains unanswered:</p><p>How does an agent decide whether a decision is good or bad?</p><p>Consider our maze-solving robot from Part 1. Imagine the robot is standing at a junction with multiple paths available.</p><p>How should it decide which path to take?</p><p>Should it choose the path that gives the highest immediate reward?</p><p>Or should it choose a path that may seem less rewarding now but leads to a much better outcome later?</p><p>To answer these questions, RL introduces the concept of value functions.</p><p>In this blog, we will understand value functions, the Bellman Equation, and two important learning approaches: Monte Carlo Learning and Temporal Difference Learning. These concepts form the foundation of many value-based Reinforcement Learning algorithms and prepare us for the next article on Q-Learning.</p><h3>Why Do We Need Value Functions?</h3><p>Imagine you are visiting a city for the first time. You want to reach a famous tourist destination, but you are unfamiliar with the roads.</p><p>At every junction, you must make a decision.</p><p>Some roads may look attractive initially but lead to dead ends. Others may appear longer but eventually lead to the destination.</p><p>After exploring the city for a few days, you naturally start developing an intuition.</p><p>You begin to think:</p><p>“This area seems close to the destination.”</p><p>“Whenever I reach this road, I usually find my way quickly.”</p><p>“This street often leads me in the wrong direction.”</p><p>You are essentially assigning a value to different locations.</p><p>Reinforcement Learning agents do exactly the same thing.</p><p>Instead of memorizing every possible path, they learn which situations are more promising and which ones should be avoided.</p><p>This is where value functions come in.</p><p>A value function helps an agent estimate how beneficial a situation is in the long run.</p><h3>State Value Function</h3><p>A State Value Function answers a simple question:</p><p><strong>“How good is it to be in this state?”</strong></p><p>Let us return to our maze example.</p><p>Imagine the robot is standing one step away from the exit.</p><p>Most of us would agree that this is a very good position to be in.</p><p>Now imagine the robot is stuck in a corner far away from the exit.</p><p>This situation is clearly less desirable.</p><p>Even without knowing the exact path ahead, we can intuitively say that some states are better than others.</p><p>The State Value Function captures this intuition numerically.</p><p>Higher values indicate states that are likely to lead to higher future rewards.</p><p>Lower values indicate states that are less promising.</p><p>The agent gradually learns these values through experience.</p><h3>Action Value Function</h3><p>Knowing whether a state is good is useful, but often it is not enough.</p><p>Suppose the robot is standing at an intersection.</p><p>From that location, it can:</p><ul><li>Move left</li><li>Move right</li><li>Move forward</li></ul><p>Even though the robot is in the same state, each action may lead to a different outcome.</p><p>One action may move the robot closer to the exit.</p><p>Another may lead to a dead end.</p><p>A third may simply waste time.</p><p>This leads to the Action Value Function.</p><p>An Action Value Function answers:</p><p><strong>“How good is it to take a particular action in this state?”</strong></p><p>Instead of evaluating only the situation, the agent evaluates both the situation and the action.</p><p>This idea becomes extremely important later when we study Q-Learning.</p><h3>Thinking Beyond Immediate Rewards</h3><p>One of the biggest challenges in Reinforcement Learning is that the best decision is not always the one that gives the largest reward immediately.</p><p>Imagine you are playing a treasure-hunting game.</p><p>You have two choices:</p><ul><li>Open a nearby chest and receive 10 coins.</li><li>Follow a longer path that eventually leads to 100 coins.</li></ul><p>If you only focus on immediate rewards, you will always choose the first option.</p><p>However, if you think about the future, the second option is clearly better.</p><p>Humans naturally think this way.</p><p>We often sacrifice short-term gains for larger future benefits.</p><p>Reinforcement Learning agents must learn to do the same.</p><p>This is why RL focuses on cumulative rewards rather than immediate rewards.</p><h3>Understanding the Bellman Equation</h3><p>Now we arrive at one of the most important ideas in Reinforcement Learning.</p><p>Suppose someone asks:</p><p>“How valuable is this state?”</p><p>One possible answer is:</p><p>“The value of this state depends on the reward I receive now and the value of the next state I will reach.”</p><p>This simple idea forms the foundation of the Bellman Equation.</p><p>Instead of trying to calculate the entire future at once, we break the problem into smaller pieces.</p><p>The value of today depends on:</p><ul><li>The reward received today</li><li>The expected value of tomorrow</li></ul><p>This recursive thinking allows RL agents to estimate long-term rewards efficiently.</p><p>The Bellman Equation is simply a mathematical way of expressing this idea.</p><p>A simplified version can be written as:</p><p><strong>Value of Current State = Immediate Reward + Discounted Value of Future State</strong></p><p>Do not worry too much about the mathematics at this stage.</p><p>The key takeaway is that the future matters.</p><p>An agent should not only evaluate the reward it receives now but also consider what that reward may lead to later.</p><h3>Learning from Experience</h3><p>Now that we understand value functions, an important question arises.</p><p>How does the agent actually learn these values?</p><p>There are several approaches, but two of the most important are:</p><ul><li>Monte Carlo Learning</li><li>Temporal Difference Learning</li></ul><p>Both methods learn from experience, but they do so in different ways.</p><h3>Monte Carlo Learning</h3><p>Monte Carlo Learning is similar to how many humans learn.</p><p>Imagine you try a completely new restaurant.</p><p>You do not judge the experience after the first bite.</p><p>Instead, you finish the entire meal and then decide whether the experience was good or bad.</p><p>Monte Carlo Learning follows the same idea.</p><p>The agent waits until the episode is completely finished.</p><p>Only after reaching the final outcome does it calculate the total reward and update its estimates.</p><p>For our maze example, the robot would wait until it either reaches the exit or fails completely.</p><p>Then it evaluates how successful the journey was.</p><h3>Advantages</h3><ul><li>Simple to understand</li><li>Learns from actual outcomes</li><li>Does not require knowledge of the environment</li></ul><h3>Limitations</h3><ul><li>Must wait until the episode ends</li><li>Learning can be slow for long tasks</li></ul><h3>Temporal Difference Learning</h3><p>Temporal Difference Learning takes a different approach.</p><p>Instead of waiting until the journey is over, it learns continuously.</p><p>Imagine learning to drive a car.</p><p>You do not wait until the end of the year to improve your driving skills.</p><p>Every time you make a mistake, you immediately adjust your behavior.</p><p>Temporal Difference Learning works in the same way.</p><p>After every action, the agent updates its estimate based on the reward received and its current prediction of the future.</p><p>For the maze robot, every movement becomes a learning opportunity.</p><p>This often leads to faster learning because feedback is incorporated immediately.</p><h3>Advantages</h3><ul><li>Learns after every interaction</li><li>Usually learns faster than Monte Carlo methods</li><li>Works well for continuing tasks</li></ul><h3>Limitations</h3><ul><li>Relies on estimates that may not always be accurate</li><li>Early learning can be noisy</li></ul><h3>Monte Carlo vs Temporal Difference Learning</h3><p>The difference between the two approaches is quite simple.</p><p>Monte Carlo Learning waits until the entire experience is completed before learning.</p><p>Temporal Difference Learning learns continuously during the experience.</p><p>A useful way to think about it is:</p><p><strong>Monte Carlo learns after the journey.</strong></p><p><strong>Temporal Difference learns during the journey.</strong></p><p>Both approaches are important, and many modern RL algorithms build upon these ideas.</p><h3>Key Takeaways</h3><ul><li>Value functions help agents estimate long-term rewards.</li><li>State values measure how good a situation is.</li><li>Action values measure how good a specific action is in a given situation.</li><li>The Bellman Equation helps estimate future rewards recursively.</li><li>Monte Carlo Learning waits until an episode finishes before learning.</li><li>Temporal Difference Learning updates estimates after every interaction.</li><li>Modern value-based algorithms are built on these foundational ideas.</li></ul><h3>Conclusion</h3><p>In this article, we explored how Reinforcement Learning agents estimate future rewards and evaluate decisions.</p><p>We introduced state values, action values, the Bellman Equation, and two important learning approaches: Monte Carlo Learning and Temporal Difference Learning.</p><p>These concepts form the foundation of many value-based Reinforcement Learning algorithms.</p><p>At this point, we know how to estimate the value of states and actions. The next question is: how can an agent use these values to learn the best action in every situation?</p><p>In the next blog, we will answer that question by introducing Q-Learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03974452acef" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/understanding-value-functions-bellman-equation-and-learning-in-reinforcement-learning-03974452acef">Understanding Value Functions, Bellman Equation, and Learning in Reinforcement Learning</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning: Learning Through Trial and Error]]></title>
            <link>https://blog.gopenai.com/reinforcement-learning-learning-through-trial-and-error-353559520b14?source=rss-fa05ca8ae5a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/353559520b14</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-reinforcement]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Maanjunath S Naragund]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 20:16:00 GMT</pubDate>
            <atom:updated>2026-06-12T20:16:00.826Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Machine Learning is often associated with tasks such as image classification, sentiment analysis, or predicting house prices. In these problems, a model learns from historical data and makes predictions.</p><p>However, many real-world problems involve making a sequence of decisions. A decision made today can influence what happens next. This is where Reinforcement Learning (RL) becomes useful.</p><p>Unlike supervised learning, where models learn from labeled examples, RL agents learn by interacting with an environment and receiving feedback on their actions. Over time, they learn which actions lead to better outcomes.</p><p>In this blog, we will explore the fundamentals of Reinforcement Learning, understand its framework, discuss different types of RL tasks, and see how Deep Learning extends traditional RL.</p><h3>What is Reinforcement Learning?</h3><p>Reinforcement Learning is a branch of Machine Learning where an agent learns through trial and error.</p><p>The agent interacts with an environment, takes actions, receives rewards, and gradually improves its decision-making strategy.</p><p>To understand the concepts throughout this blog, consider a simple maze-solving robot.</p><p>The robot starts at the entrance of a maze and must find the exit. Initially, it does not know the correct path. It moves around, explores different routes, hits dead ends, and eventually discovers which path leads to the goal.</p><p>After many attempts, the robot becomes better at navigating the maze and reaches the exit more efficiently.</p><p>This is the basic idea behind Reinforcement Learning. The agent learns from experience instead of being explicitly told what to do.</p><p>The ultimate goal is to maximize the total reward collected over time.</p><h3>The Reinforcement Learning Framework</h3><p>A Reinforcement Learning system consists of several key components.</p><h3>Agent</h3><p>The agent is the learner or decision-maker.</p><p>In our example, the robot navigating the maze is the agent.</p><h3>Environment</h3><p>The environment is everything the agent interacts with.</p><p>For the robot, the maze itself is the environment.</p><h3>State</h3><p>A state represents the current situation of the agent within the environment.</p><p>For example, the robot’s current position in the maze can be considered its state.</p><h3>Action</h3><p>An action is a decision made by the agent.</p><p>The robot may choose actions such as:</p><ul><li>Move up</li><li>Move down</li><li>Move left</li><li>Move right</li></ul><h3>Reward</h3><p>A reward is feedback received from the environment after taking an action.</p><p>Rewards help the agent understand whether its actions are good or bad.</p><h3>How Are Rewards Calculated?</h3><p>One common misconception is that RL algorithms automatically know what rewards should be.</p><p>In reality, rewards are designed by the person creating the problem.</p><p>For our maze example, we might define:</p><ul><li>+100 for reaching the exit</li><li>-10 for hitting a wall</li><li>-1 for each step taken</li></ul><p>These values are not fixed rules. They are chosen to encourage desired behavior.</p><p>Giving a positive reward for reaching the exit motivates the robot to complete the task. Giving a small penalty for each step encourages it to find shorter paths instead of wandering around the maze.</p><p>Designing an effective reward function is one of the most important aspects of Reinforcement Learning.</p><h3>Policy</h3><p>A policy is the strategy used by the agent to decide which action to take in a given state.</p><p>In simple terms, a policy answers the question:</p><p>“What should I do next?”</p><p>As the agent learns, its policy improves.</p><h3>The RL Interaction Loop</h3><p>The learning process follows a simple cycle:</p><ol><li>Observe the current state.</li><li>Select an action.</li><li>Receive a reward.</li><li>Move to a new state.</li><li>Repeat.</li></ol><p>Through repeated interactions, the agent gradually learns a better policy.</p><h3>State vs Observation</h3><p>Many beginners use the terms state and observation interchangeably, but they are not always the same.</p><p>A state contains all the information needed to completely describe the environment at a given moment.</p><p>An observation is the information that is actually available to the agent.</p><p>Imagine our maze-solving robot has access to the complete map of the maze and knows its exact location. In this case, the robot can observe the full state.</p><p>Now imagine the robot only has a small camera that shows nearby cells. The robot can only see a portion of the maze at any given time.</p><p>The complete maze still represents the state of the environment, but the camera input is only an observation.</p><p>In many real-world applications, agents learn from observations because the complete state is often unavailable.</p><h3>Types of Reinforcement Learning Tasks</h3><p>Reinforcement Learning problems are commonly categorized into two types.</p><h3>Episodic Tasks</h3><p>An episodic task has a clear starting point and ending point.</p><p>In our maze example, an episode starts when the robot enters the maze and ends when it reaches the exit.</p><p>Once the task is completed, a new episode can begin.</p><p>Examples include:</p><ul><li>Board games</li><li>Video games</li><li>Maze solving</li></ul><h3>Continuing Tasks</h3><p>A continuing task does not have a natural ending.</p><p>The agent continuously interacts with the environment and keeps making decisions.</p><p>Examples include:</p><ul><li>Recommendation systems</li><li>Traffic management</li><li>Inventory optimization</li></ul><p>The goal is to maximize long-term rewards over an ongoing period.</p><h3>Exploration vs Exploitation</h3><p>One of the most important challenges in Reinforcement Learning is balancing exploration and exploitation.</p><h3>Exploration</h3><p>Exploration means trying actions that the agent has not tried before.</p><p>The goal is to gather more information about the environment.</p><p>In the maze example, the robot may choose a path it has never visited before. The path may be better or worse, but the robot gains new knowledge.</p><h3>Exploitation</h3><p>Exploitation means using the knowledge already learned to maximize rewards.</p><p>If the robot already knows a path that usually leads to the exit, it may choose that path repeatedly.</p><p>This often provides higher immediate rewards.</p><h3>The Exploration-Exploitation Trade-Off</h3><p>If the agent only explores, it spends too much time trying random actions and may never take advantage of what it has learned.</p><p>If the agent only exploits, it may miss better solutions that it has not yet discovered.</p><p>A successful RL agent balances both exploration and exploitation.</p><p>Typically, exploration is more common during the early stages of training, while exploitation becomes more common as the agent gains experience.</p><h3>The “Deep” in Deep Reinforcement Learning</h3><p>Traditional Reinforcement Learning works well when the number of states and actions is relatively small.</p><p>However, many real-world problems involve enormous state spaces.</p><p>Consider a robot that receives camera images instead of a simple location value. Each image may contain thousands or even millions of pixel values.</p><p>Representing and learning from such large inputs becomes difficult using traditional RL approaches.</p><p>This is where Deep Reinforcement Learning comes in.</p><p>Deep Reinforcement Learning combines Reinforcement Learning with Deep Learning.</p><p>Neural networks are used to learn useful representations from large and complex inputs such as:</p><ul><li>Images</li><li>-Video</li><li>Audio</li><li>Sensor data</li></ul><p>Instead of manually defining every possible situation, the neural network learns patterns directly from the data.</p><p>This enables RL systems to solve much more complex problems.</p><h3>Value-Based vs Policy-Based Methods</h3><p>As Reinforcement Learning evolved, researchers developed different approaches for learning.</p><p>Two of the most common approaches are value-based methods and policy-based methods.</p><h3>Value-Based Methods</h3><p>Value-based methods learn how good a state or action is.</p><p>The agent estimates a value and chooses actions that are expected to provide the highest reward.</p><p>In simple terms, the agent learns:</p><p>“What is the value of taking this action?”</p><p>and then chooses the action with the highest estimated value.</p><h3>Policy-Based Methods</h3><p>Policy-based methods learn the policy directly.</p><p>Instead of estimating action values first, the model directly learns which action should be taken in a given situation.</p><p>In simple terms, the agent learns:</p><p>“What action should I take in this situation?”</p><h3>Which Approach Is Better?</h3><p>There is no universal answer.</p><p>Value-based methods are often easier to understand and work well for many problems.</p><p>Policy-based methods are useful when the action space becomes large or continuous.</p><p>Modern Reinforcement Learning algorithms often combine ideas from both approaches.</p><h3>Key Takeaways</h3><ul><li>Reinforcement Learning is a learning paradigm based on trial and error.</li><li>Agents learn by interacting with an environment and receiving rewards.</li><li>The RL framework consists of Agent, Environment, State, Action, Reward, and Policy.</li><li>State and observation are related but not always the same.</li><li>RL tasks can be episodic or continuing.</li><li>Exploration and exploitation must be balanced for effective learning.</li><li>Deep Reinforcement Learning combines RL with neural networks to handle complex inputs.</li></ul><p>Modern RL approaches are commonly based on value functions, policies, or a combination of both.</p><h3>Conclusion</h3><p>Reinforcement Learning is one of the most exciting areas of Machine Learning because it focuses on learning through experience.</p><p>Rather than simply making predictions, RL agents learn how to make decisions that maximize long-term rewards. Although advanced RL algorithms can become mathematically complex, the underlying idea remains simple: interact with the environment, learn from feedback, and improve over time.</p><p>Understanding these fundamentals provides a strong foundation for exploring more advanced topics such as Q-Learning, Policy Gradient methods, and modern Deep Reinforcement Learning systems.s</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=353559520b14" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/reinforcement-learning-learning-through-trial-and-error-353559520b14">Reinforcement Learning: Learning Through Trial and Error</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Train a Kannada Tokenizer for LLaMA 3.2–1B Using SentencePiece]]></title>
            <link>https://blog.gopenai.com/train-a-kannada-tokenizer-for-llama-3-2-1b-using-sentencepiece-3b59aee68259?source=rss-fa05ca8ae5a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b59aee68259</guid>
            <category><![CDATA[custom-tokenizer]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[indian-languages]]></category>
            <category><![CDATA[sentencepiece]]></category>
            <category><![CDATA[kannada-nlp]]></category>
            <dc:creator><![CDATA[Maanjunath S Naragund]]></dc:creator>
            <pubDate>Sat, 26 Jul 2025 07:05:32 GMT</pubDate>
            <atom:updated>2025-08-01T15:23:06.723Z</atom:updated>
            <content:encoded><![CDATA[<p>As someone interested in applying advanced AI to support <strong>Bharat’s diverse linguistic landscape</strong>, I’ve been diving deep into how we can adapt powerful Large Language Models (LLMs) like Meta’s LLaMA 3.2 for Indian languages. While LLaMA 3.2 supports many languages well, out of the box performance for languages like my native <strong>Kannada</strong> can still leave room for improvement.</p><p>That’s why I embarked on a project to create a custom tokenizer designed to work hand in hand with Llama 3.2–1B, focusing specifically on Kannada. Today, I’m excited to share the insights and approach behind my <strong>Kannada Tokenizer extension</strong> for <strong>Llama 3.2–1B</strong>!</p><p>Dataset used: <a href="https://www.kaggle.com/datasets/disisbig/kannada-wikipedia-articles">Kannada</a>. You can refer this dataset.</p><h3>Why Extend Llama’s Tokenizer for Kannada?</h3><p>LLaMA 3.2 models use <strong>SentencePiece</strong> natively a great choice for multilingual tasks. But Indian languages like Kannada, which are <strong>morphologically rich</strong>, benefit immensely from more tailored tokenization. The default tokenizer doesn’t segment Kannada words meaningfully breaking them into fragmented Unicode sequences that don’t align with Kannada’s natural word structure..</p><p>The goal wasn’t to replace Llama’s tokenizer entirely, but to <strong>enhance it</strong>. By extending its existing vocabulary with Kannada specific subword units, we can:</p><ul><li><strong>Improve tokenization efficiency:</strong> Kannada words are broken down into more meaningful, language aware pieces, leading to shorter, more relevant token sequences.</li><li><strong>Reduce Out Of Vocabulary (OOV) tokens:</strong> By using a custom tokenizer trained on Kannada (e.g., with SentencePiece), we get clean, meaningful subwords instead.</li></ul><p>Example:</p><ul><li><strong>Without custom tokenization:</strong> à², ķ, à², ¨, à³, į, ...</li><li><strong>With custom tokenizer:</strong> [&#39;ಕನ್ನಡ&#39;, &#39;ವು&#39;, &#39;▁&#39;, &#39;ಒಂದು&#39;, &#39;▁&#39;, &#39;ಸುಂದರ&#39;, &#39;▁&#39;, &#39;ಭಾಷೆ&#39;, &#39;.&#39;]</li><li><strong>Maintain compatibility:</strong> By sticking to SentencePiece and extending, we ensure seamless integration with the Llama 3.2 architecture.</li></ul><h3>The Power of SentencePiece for Indian Languages</h3><p>Indian languages like Kannada have <strong>rich morphology </strong>where a single root word can take many forms through suffixes, prefixes, or sandhi. This makes traditional tokenization approaches inefficient.</p><p>That’s where <strong>SentencePiece</strong> shines:</p><ul><li><strong>Subword level segmentation</strong>: Whether using BPE or Unigram, SentencePiece can break down complex words into reusable subword units.</li><li><strong>Whitespace agnostic</strong>: SentencePiece treats text as a raw stream of characters with no need for pretokenization. This is particularly helpful for Indian scripts, where word boundaries can be fuzzy or inconsistent.</li><li><strong>Mixed script support</strong>: It handles multilingual or mixed language sentences (like Kannada + English) without issues.</li></ul><p>In my case, I used <strong>SentencePiece with the BPE algorithm</strong>, which greedily merges frequent subword pairs optimized for Kannada.</p><h3>My Approach: Extending the Llama 3.2–1B Tokenizer</h3><p>Here’s the high level process I followed to create imanjunathn/Llama-3.2-1B-Kannada-Tokenizer:</p><ol><li><strong>Start with the Original:</strong> I began by loading the official meta-llama/Llama-3.2-1B tokenizer.</li><li><strong>Train a New Kannada Specific Model:</strong> I then trained a <em>new</em> SentencePiece BPE model on a substantial and Kannada text corpus (including Wikipedia). This new model was designed to discover optimal Kannada subword units.</li><li><strong>Identify Unique Tokens:</strong> The crucial step was to compare the vocabulary of my newly trained Kannada SentencePiece model with the original Llama 3.2 tokenizer’s vocabulary. I identified all the unique Kannada subword tokens that were <em>not</em> present in Llama’s original set.</li><li><strong>Extend the Original Tokenizer:</strong> These unique Kannada tokens were then added to the <em>original</em> Llama 3.2–1B tokenizer’s vocabulary. This effectively “teaches” the existing tokenizer how to better handle Kannada.</li><li><strong>Save the Enhanced Tokenizer:</strong> The final, extended tokenizer was saved, ready to be used.</li></ol><h3>How to Use the Enhanced Tokenizer</h3><p>You can find and use this specialized tokenizer directly from the Hugging Face Hub: imanjunathn/Llama-3.2-1B-Kannada-Tokenizer.</p><pre>from transformers import AutoTokenizer, AutoModelForCausalLM<br>import torch<br><br><br># Define the paths<br># Your base Llama 3.2 model<br>model_id = &quot;meta-llama/Llama-3.2-1B&quot; <br># Your custom tokenizer<br>tokenizer_id = &quot;imanjunathn/Llama-3.2-1B-Kannada-Tokenizer&quot; <br># 1. Load the original Llama 3.2 model<br># model = AutoModelForCausalLM.from_pretrained(model_id)<br><br># 2. Load the extended Kannada tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)<br><br># 3. If you were continually pre training or fine-tuning, you would resize embeddings:<br>#  model.resize_token_embeddings(len(tokenizer))<br><br># Example Kannada text<br>kannada_text = &quot;ನಮಸ್ಕಾರ ಕನ್ನಡ ಭಾಷೆ. ನನ್ನ email ID ಇದು example@email.com ಆಗಿದೆ.&quot;<br><br># Tokenize the text<br>encoded_input = tokenizer(kannada_text, return_tensors=&quot;pt&quot;, add_special_tokens=True)<br>print(&quot;Original Text:&quot;, kannada_text)<br>print(&quot;Encoded Token IDs:&quot;, encoded_input[&#39;input_ids&#39;][0].tolist())<br># Decode the tokens back to text<br>decoded_text = tokenizer.decode(encoded_input[&#39;input_ids&#39;][0], skip_special_tokens=True)<br>print(&quot;Decoded Text:&quot;, decoded_text)<br># Inspect the tokens themselves (useful for understanding segmentation)<br>tokens = tokenizer.convert_ids_to_tokens(encoded_input[&#39;input_ids&#39;][0].tolist())<br>print(&quot;Tokens (including special tokens and SentencePiece prefixes):&quot;, tokens)</pre><h3>Performance and Test Results</h3><p>I put this extended tokenizer through rigorous testing across various Kannada text types:</p><h4><strong>Without Kannada Tokens (Base LLaMA Tokenizer)</strong></h4><ul><li><strong>Original:</strong> “ಕನ್ನಡವು ಒಂದು ಸುಂದರ ಭಾಷೆ.”</li><li><strong>Tokens:</strong> [‘à²’, ‘ķ’, ‘à²’, ‘¨’, ‘à³’, ‘į’, ‘à²’, ‘¨’, ‘à²’, ‘¡’, ‘à²’, ‘µ’, ‘à³’, ‘ģ’, ‘Ġà²’, ‘Ĵ’, ‘à²’, ‘Ĥ’, ‘à²’, ‘¦’, ‘à³’, ‘ģ’, ‘Ġà²’, ‘¸’, ‘à³’, ‘ģ’, ‘à²’, ‘Ĥ’, ‘à²’, ‘¦’, ‘à²’, ‘°’, ‘Ġà²’, ‘Ń’, ‘à²’, ‘¾’, ‘à²’, ‘·’, ‘à³’, ‘Ĩ’, ‘.’, ‘Ġà²’, ‘¬’, ‘à³’, ‘Ĩ’, ‘à²’, ‘Ĥ’, ‘à²’, ‘Ĺ’, ‘à²’, ‘³’, ‘à³’, ‘Ĥ’, ‘à²’, ‘°’, ‘à³’, ‘ģ’, ‘Ġà²’, ‘ķ’, ‘à²’, ‘°’, ‘à³’, ‘į’, ‘à²’, ‘¨’, ‘à²’, ‘¾’, ‘à²’, ‘Ł’, ‘à²’, ‘ķ’, ‘à²’, ‘¦’, ‘Ġà²’, ‘°’, ‘à²’, ‘¾’, ‘à²’, ‘ľ’, ‘à²’, ‘§’, ‘à²’, ‘¾’, ‘à²’, ‘¨’, ‘à²’, ‘¿’, ‘.’]</li><li><strong>Decoded:</strong> “ಕನ್ನಡವು ಒಂದು ಸುಂದರ ಭಾಷೆ.”</li><li><strong>Analysis:</strong> Tokens are byte level junk, leading to longer sequences and poor semantic understanding.</li></ul><h4>Pure Kannada</h4><p><strong>Test Case 1: Basic sentence</strong></p><ul><li><strong>Original text:</strong> “ನಮಸ್ಕಾರ ಕನ್ನಡ ಭಾಷೆ.” (Hello Kannada language)</li><li><strong>Tokens: </strong>[‘ನ’, ‘ಮಸ್’, ‘ಕಾರ’, ‘Ġ’, ‘ಕನ್ನಡ’, ‘Ġ’, ‘ಭಾಷೆ’, ‘.’]</li><li><strong>Token IDs :</strong> [128000, 128273, 132982, 128875, 220, 130527, 220, 132338, 13] (IDs would vary based on actual vocabulary)</li><li><strong>Decoded text:</strong> “ನಮಸ್ಕಾರ ಕನ್ನಡ ಭಾಷೆ.”</li><li><strong>Analysis:</strong> Perfect reconstruction, efficient subword segmentation that respects Kannada morphology.</li></ul><p><strong>Test Case 2: Complex sentence</strong></p><ul><li><strong>Original text:</strong> “ಕನ್ನಡ ನಾಡಿನ ಸಂಸ್ಕೃತಿ ಮತ್ತು ಪರಂಪರೆ” (Kannada land&#39;s culture and heritage)</li><li><strong>Tokens: </strong>[‘ಕನ್ನಡ’, ‘Ġ’, ‘ನಾಡಿನ’, ‘Ġ’, ‘ಸಂಸ್ಕೃತಿ’, ‘Ġ’, ‘ಮತ್ತು’, ‘Ġ’, ‘ಪರಂಪರೆ’]</li><li><strong>Token IDs (example):</strong> [128000, 130527, 220, 138791, 220, 143433, 220, 129696, 220, 147021]</li><li><strong>Decoded text:</strong> “ಕನ್ನಡ ನಾಡಿನ ಸಂಸ್ಕೃತಿ ಮತ್ತು ಪರಂಪರೆ”</li><li><strong>Analysis:</strong> Handles complex words and compound structures effectively, ensuring high fidelity encoding and decoding.</li></ul><h4>Mixed Language (Kannada with English)</h4><ul><li><strong>Test Case:</strong> “ನನ್ನ email ID ಇದು <a href="/service/mailto:example@email.com">example@email.com</a> ಆಗಿದೆ” (My email ID is example@email.com)</li><li><strong>Tokens: </strong>[‘ನನ್ನ’, ‘Ġemail’, ‘ĠID’, ‘Ġ’, ‘ಇದು’, ‘Ġexample’, ‘@email’, ‘.com’, ‘Ġ’, ‘ಆಗ’, ‘ಿದೆ’]</li><li><strong>Token IDs:</strong> [128000, 135800, 2613, 3110, 220, 128886, 3187, 72876, 916, 220, 133560, 128398]</li><li><strong>Decoded text:</strong> “ನನ್ನ email ID ಇದು <a href="/service/mailto:example@email.com">example@email.com</a> ಆಗಿದೆ”</li><li><strong>Analysis:</strong> Seamlessly integrates Kannada script with English words, numbers, and special characters, demonstrating robust mixed language handling.</li></ul><p>My testing also covered numbers, dates, punctuation, and various edge cases like URLs and emojis, all demonstrating the tokenizer’s comprehensive capabilities.</p><h3>What’s Next? Enabling Llama 3.2–1B for Kannada!</h3><p>This extended tokenizer is a crucial first step. To fully leverage its potential, the next phase involves <strong>continual pre training or fine-tuning</strong> of the Llama 3.2–1B model on a substantial Kannada dataset. This will allow the model to learn and embed the meanings of the newly added Kannada subword tokens, integrating them into its vast linguistic knowledge.</p><p>This work aims to ensure that LLMs don’t just “support” Kannada in a superficial way, but truly understand and generate text in the language with the fluency and nuance it deserves.</p><h3>Summary</h3><p>I’ve successfully enhanced Llama 3.2–1B’s capabilities for Kannada. By extending its native SentencePiece tokenizer with custom Kannada vocabulary. This means Llama 3.2 can now understand Kannada better, learn faster during fine-tuning tasks. This method offers a clear path for adapting powerful LLMs to any Indian language, making advanced AI truly accessible for every voice in India.</p><p>If you’re working with any Indian language (Marathi, Tamil, etc.), you can <strong>replicate this exact process</strong>.</p><p><strong>Try it yourself</strong>: <a href="https://huggingface.co/imanjunathn/Llama-3.2-1B-Kannada-Tokenizer">imanjunathn/Llama-3.2–1B-Kannada-Tokenizer</a></p><h3>References</h3><ul><li><a href="https://www.tensoic.com/blog/kannada-llama/">https://www.tensoic.com/blog/kannada-llama/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b59aee68259" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/train-a-kannada-tokenizer-for-llama-3-2-1b-using-sentencepiece-3b59aee68259">Train a Kannada Tokenizer for LLaMA 3.2–1B Using SentencePiece</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformer Multi-Head Attention Implementation in TensorFlow with Scaled Dot Product]]></title>
            <link>https://blog.gopenai.com/transformer-multi-head-attention-implementation-in-tensorflow-with-scaled-dot-product-6f391ccfa758?source=rss-fa05ca8ae5a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f391ccfa758</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[transformer-model]]></category>
            <category><![CDATA[multi-head-attention]]></category>
            <dc:creator><![CDATA[Maanjunath S Naragund]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 15:13:27 GMT</pubDate>
            <atom:updated>2024-10-24T14:32:51.506Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of modern machine learning, especially in models like transformers (BERT, GPT etc), <strong>Attention </strong>mechanisms play a pivotal role. Among them, <strong>Multi-Head Attention </strong>(MHA) is a core building block that allows a model to focus on different parts of the input sequence simultaneously.</p><p>In this blog, I’ll show you how to implement multi-head attention from scratch using TensorFlow and Keras. If you’ve been curious about how transformers “pay attention,” by the end of this post, you’ll have a hands-on understanding of it. we’ll walk through it step by step!</p><p>Here’s what we will cover:</p><ol><li><strong>Dot Product Attention: </strong>The mechanism behind the attention scores.</li><li><strong>Multi-Head Attention: </strong>The extension of dot product attention to multiple heads for better information extraction.</li></ol><p>You can find the complete code on <a href="https://github.com/imanjunathn/multi-head-attention-tensorflow">GitHub</a> here.</p><p>Let’s get started by first understanding the foundation of the attention mechanism: <strong>Scaled Dot Product Attention.</strong></p><h4><strong>Scaled Dot Product Attention</strong></h4><p>the attention mechanism revolves around the queries(q), keys(k), and values(v). The essence of attention is to determine how much focus each part of the sequence should have on every other part. The <strong>dot product</strong> between queries and keys gives us <strong>attention scores</strong>, which dictate this focus.</p><p>Imagine you’re reading a sentence — your attention shifts from one word to another, right? Queries represent what you’re looking at, keys represent everything in the sequence you could focus on, and values represent the meaning you extract.</p><p>To ensure that these attention scores do not become too large and destabilize training, they are <strong>scaled by the square of the dimension of the keys(dk).</strong> This scaling helps in maintaining stable gradients during backpropagation and ensures smoother learning, especially when the dimensionality of the keys is large.</p><p>The formula for calculating scaled attention scores is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*eSti-jO8OtIMOTH2sW4LgA.png" /></figure><p>Where:</p><ol><li>q and k are query and key matrices</li><li>dk is the dimension of the keys.</li></ol><h4><strong>Code for the Dot Product Attention:</strong></h4><pre>import tensorflow as tf<br>from tensorflow.keras.layers import Layer<br><br>class DotProductAttention(Layer):<br>    def __init__(self, **kwargs):<br>        super(DotProductAttention, self).__init__(**kwargs)<br>    <br>    def call(self, q, k, v, mask=None):   <br>        dk = tf.cast(tf.shape(k)[-1], tf.float32)  # Dimension of key for scaling<br>        matmul_qk = tf.matmul(q, k, transpose_b=True)  # Dot product of query and key<br>        <br>        # Scale by the square root of key dimension to avoid overly large gradients<br>        scores = matmul_qk / tf.math.sqrt(dk)<br>        <br>        # Optional mask to prevent attending to certain positions (e.g., padding)<br>        if mask is not None:<br>            scores += (-1e9 * mask)  # Masking unwanted positions<br>        <br>        # Apply softmax to get attention weights<br>        weights = tf.nn.softmax(scores, axis=-1)<br>        <br>        # Weighted sum of the values using attention weights<br>        return tf.matmul(weights, v)</pre><p>This snippet implements dot product attention in TensorFlow, the query(q), key(k), and value(v) are passed through a dot product calculation. The result is scaled, optionally masked, and then fed into softmax to generate attention scores. These scores determine which values(v) are focused on.</p><h4><strong>Multi-Head Attention</strong></h4><p>While a single dot product attention can capture one relationship in the sequence, <strong>Multi-Head Attention </strong>allows the model to learn different representations by splitting the input into multiple heads. Each head performs scaled dot attention independently, and their outputs are concatenated to form a more nuanced representation.</p><p>Imagine you’re trying to understand a conversation. You focus not only on the words being spoken but also on the tone and body language. Each head in multi-head attention does something similar — each one focuses on different patterns in the data.</p><h4><strong>Multi-Head Attention Implementation:</strong></h4><pre>from tensorflow.keras.layers import Dense<br><br>class MultiHeadAttention(Layer):<br>    def __init__(self, d_model, number_heads):<br>        super(MultiHeadAttention, self).__init__()<br>        <br>        self.d_model = d_model<br>        self.num_heads = number_heads<br>        <br>        # Ensure the model dimensionality is divisible by the number of heads<br>        assert d_model % number_heads == 0, &quot;d_model must be divisible by number_heads&quot;<br>        <br>        # Dimension of each head (depth)<br>        self.depth = d_model // number_heads<br>        <br>        # Linear layers for query, key, value transformations<br>        self.wq = Dense(d_model)<br>        self.wk = Dense(d_model)<br>        self.wv = Dense(d_model)<br>        <br>        # Output layer to project the concatenated attention outputs<br>        self.dense = Dense(d_model)<br>        <br>        # Dot product attention mechanism<br>        self.attention = DotProductAttention()<br>    <br>    def reshape_tensor(self, x, batch_size, flag=False):<br>        if flag:<br>            # Split into multiple heads and rearrange dimensions for attention<br>            # (batch_size, heads, seq_length, -1)<br>            x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))<br>            return tf.transpose(x, perm=(0, 2, 1, 3))<br>        else:    <br>            # Merge heads back to original shape<br>            x = tf.transpose(x, perm=(0, 2, 1, 3))<br>            # (batch_size, seq_length, model dimension)<br>            return tf.reshape(x, (batch_size, -1, self.d_model))<br>    <br>    def call(self, q, k, v, mask=None):<br>        batch_size = tf.shape(q)[0]<br>        <br>        # Linear transformations for query, key, value<br>        wq = self.wq(q)<br>        wk = self.wk(k)<br>        wv = self.wv(v)<br>        <br>        # Split and reshape for multi-head attention<br>        q = self.reshape_tensor(wq, batch_size, True)<br>        k = self.reshape_tensor(wk, batch_size, True)<br>        v = self.reshape_tensor(wv, batch_size, True)<br>        <br>        # Perform scaled dot product attention<br>        scaled_attention = self.attention(q, k, v, mask)<br>        <br>        # Reshape the output back from heads to original dimensions<br>        output = self.reshape_tensor(scaled_attention, batch_size)<br>        <br>        return self.dense(output)</pre><p>Here, each of the <strong>query, key, and value </strong>tensors is passed through a liner layer and then split into multiple heads. After performing dot product attention on each head, the results are concatenated and projected back to the original dimensionality.</p><h4><strong>Why Use Multi-Head Attention?</strong></h4><p>By splitting the attention mechanism into multiple heads, the model can focus on different parts of the input simultaneously, capturing a richer representation of the relationships within the sequence. This is especially powerful for tasks like translation, text generation, or any other problem where understanding long-range dependencies is critical.</p><h4>Putting It All Together</h4><p>Let’s test the implementation with some random data:</p><pre># Define the input tensor dimensions<br>d_model = 128  # Model dimensionality<br>num_heads = 8  # Number of attention heads<br>seq_len = 10   # Sequence length<br><br># Sample query, key, and value tensors<br>query = tf.random.normal((2, seq_len, d_model))  # (batch_size=2, seq_len, d_model)<br>key = tf.random.normal((2, seq_len, d_model))    # (batch_size=2, seq_len, d_model)<br>value = tf.random.normal((2, seq_len, d_model))  # (batch_size=2, seq_len, d_model)<br><br><br># Create the Multi-Head Attention layer<br>mha = MultiHeadAttention(d_model, num_heads)<br><br># Forward pass<br>attention_output = mha(value, key, query)<br><br>print(&quot;Attention Output Shape:&quot;, attention_output.shape)  # (batch_size, seq_len, d_model)<br># print(&quot;Attention Ouputs:&quot;, attention_output)  </pre><h4><strong>Conclusion</strong></h4><p>In this blog, we explored the implementation of <strong>Multi-Head Attention </strong>from scratch using Tensorflow. We started with <strong>Scaled Dot Product Attention </strong>and extended it to the multi-head version, which helps to capture different parts of the sequence simultaneously. This mechanism is the backbone of transformer architecture, which power state-of-the-art models like BERT and GPT.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f391ccfa758" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/transformer-multi-head-attention-implementation-in-tensorflow-with-scaled-dot-product-6f391ccfa758">Transformer Multi-Head Attention Implementation in TensorFlow with Scaled Dot Product</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BERT for NER: Extracting Key Information from Bank SMS]]></title>
            <link>https://blog.gopenai.com/bert-for-ner-extracting-key-information-from-bank-sms-993883a1127f?source=rss-fa05ca8ae5a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/993883a1127f</guid>
            <category><![CDATA[machine-learning-app]]></category>
            <category><![CDATA[named-entity-recognition]]></category>
            <category><![CDATA[ai-in-financial-services]]></category>
            <category><![CDATA[bert-for-nlp]]></category>
            <dc:creator><![CDATA[Maanjunath S Naragund]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 18:49:33 GMT</pubDate>
            <atom:updated>2024-09-27T06:38:13.123Z</atom:updated>
            <content:encoded><![CDATA[<p>BERT stands for Bidirectional Encoder Representations from Transformers. This model, introduced by Google in 2018, has completely transformed the field of natural language processing (NLP). Unlike previous models, BERT reads text bidirectionally, meaning it looks at the entire sentence from both directions to grasp the context of each word. This ability allows BERT to capture the intricate relationships and dependencies in language, making it a powerhouse for various NLP tasks — one of which is Named Entity Recognition (NER).</p><p>NER is an essential NLP task where the goal is to identify and classify entities in text, like names of people, organizations, dates, and more. It becomes particularly valuable in the financial sector, where you can use NER to extract critical information from transactional data, such as those SMS we often receive from banks.</p><h3>Architecture of BERT</h3><p>Let’s break down what makes BERT work. BERT is built on the Transformer model, a type of architecture that uses self-attention mechanisms to process input data. Unlike traditional models that read text in one direction, BERT reads it bidirectionally — looking at the whole sentence both forwards and backward. This bidirectional approach allows BERT to understand the context in a much deeper and more meaningful way.</p><h3>Key Components:</h3><ul><li><strong>Input Representation:</strong> BERT uses a combination of token embeddings, segment embeddings, and position embeddings to represent input text. It tokenizes words using something called WordPiece embeddings, which is especially useful for handling rare words by breaking them down into subwords.</li></ul><figure><img alt="Image from: BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding paper." src="https://cdn-images-1.medium.com/max/1024/1*n3RKLAPPF42l59EzOidzqQ.png" /><figcaption>Image from: “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding”</figcaption></figure><ul><li><strong>Transformer Layers:</strong> At the core of BERT are multiple transformer layers — 12 in the BERT Base model and 24 in BERT Large. These layers use self-attention to learn the relationships between words in a sentence, making sure the context is understood at a deep level.</li><li><strong>Pre-training Tasks:</strong> BERT is pre-trained on two main tasks: <strong>Masked Language Modeling (MLM) and Next Sentence Prediction (NSP).</strong></li><li><strong>Masked Language Modeling (MLM):</strong> Here, some words in a sentence are masked, and the model learns to predict them based on the context.</li><li><strong>Next Sentence Prediction (NSP):</strong> This task helps the model understand the relationship between pairs of sentences, which is crucial for grasping context.</li></ul><p>After pre-training, BERT is like a well-read student who’s ready to be fine-tuned for specific tasks like NER. You simply add a classification layer on top of the transformer outputs, and you’re good to go!</p><h3>Implementation of BERT for Named Entity Recognition</h3><p>So, how do we actually implement BERT for NER, especially in something as domain-specific as bank transaction SMS messages? Here’s a step-by-step guide: <a href="https://github.com/imanjunathn/BERT-NER-Bank-Transactions">github</a></p><h3>Step 1: Preparing the Dataset</h3><p>First things first — you need a dataset. In the case of bank transaction SMS, your dataset will contain sentences where each word is labeled with its corresponding entity, such as DATE, TIME, TRANSACTION_TYPE, BANK, MONEY, and ACCOUNT_NUMBER. This data is then processed into a format that BERT can understand, with each sentence tokenized and each token associated with a label.</p><pre># Start data preparation<br>hf_dataset = Dataset.from_pandas(pd.DataFrame(ner_sentences))<br>print(f&quot;Dataset contains {hf_dataset.num_rows} rows.&quot;)<br><br># Split the dataset into training and test sets<br>train_test_split_result = hf_dataset.train_test_split(test_size=0.1)<br>train_dataset = train_test_split_result[&#39;train&#39;]<br>test_dataset = train_test_split_result[&#39;test&#39;]<br><br>print(f&quot;Training set size: {train_dataset.num_rows}&quot;)<br>print(f&quot;Test set size: {test_dataset.num_rows}&quot;)</pre><h3>Step 2: Tokenization</h3><p>BERT uses a nifty thing called WordPiece tokenization, which breaks down words into subwords if they’re not in the vocabulary. This ensures that even rare or unfamiliar words can be represented accurately. During tokenization, special tokens like [CLS] (denoting the start of a sentence) and [SEP] (denoting the end of a sentence or segment) are added to the text.</p><pre># Load tokenizer<br>tokenizer_name = &#39;bert-base-cased&#39;<br>tokenizer = BertTokenizerFast.from_pretrained(tokenizer_name)<br>print(f&quot;Tokenizer {tokenizer_name} loaded.&quot;)<br><br><br>tokenized_train_dataset = train_dataset.map(tokenize_and_align_labels, batched=True, remove_columns=train_dataset.column_names)<br>tokenized_test_dataset = test_dataset.map(tokenize_and_align_labels, batched=True, remove_columns=test_dataset.column_names)</pre><h3>Step 3: Fine-tuning BERT</h3><p>This is where the magic happens. The fine-tuning process involves training the BERT model on your NER dataset. The model learns to classify each token based on its context, allowing it to accurately identify entities in new, unseen sentences.</p><pre>model = AutoModelForTokenClassification.from_pretrained(tokenizer_name, <br>                                                        num_labels=len(list(unique_labels)),<br>                                                        id2label=id2label, label2id=label2id)<br><br># Initialize the Trainer<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_dataset[&quot;train&quot;],<br>    eval_dataset=tokenized_dataset[&quot;test&quot;],<br>    tokenizer=tokenizer,<br>    compute_metrics=compute_metrics,<br>)<br><br># Train and evaluate the model<br>trainer.train()</pre><h3>Step 4: Evaluation and Prediction</h3><p>After training, you evaluate the model on a test set to make sure it’s accurately recognizing entities. Once you’re satisfied with the results, the model can be used to predict entities in new SMS messages, extracting valuable information for various financial applications.</p><pre>def predict(text: str):<br>    model = tuned_model<br>    model.to(device)<br>    # Tokenize the text<br>    tokens = tuned_tokenizer(text, return_tensors=&quot;pt&quot;, truncation=True, padding=True).to(device)<br><br>    # Get model predictions<br>    with torch.no_grad():<br>        outputs = model(**tokens)<br>    logits = outputs.logits<br><br>    # Get the predicted labels<br>    predictions = torch.argmax(logits, dim=-1).squeeze().cpu().tolist()<br>    tokens = tokens[&quot;input_ids&quot;].squeeze().cpu().tolist()<br><br>    # Convert predictions to label names<br>    labels = [model.config.id2label[pred] for pred in predictions]<br>#     print(labels)<br>    tokens = [tuned_tokenizer.decode([token]) for token in tokens]<br><br>    # Filter out special tokens<br>    result = [{&quot;token&quot;: token, &quot;label&quot;: label} for token, label in zip(tokens, labels) if token not in tokenizer.all_special_tokens]<br><br>    return {&quot;result&quot;: result}<br><br># Example text for prediction<br>text = &quot;399.00 spent on ICICI Bank Card XX1000 on 16-Jun-22 at Amazon. Avl Lmt: INR 1,38,768.54.&quot;<br>predict(text)[&#39;results&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*KPh_PsbqXEXSqsMa4f8B5g.png" /></figure><h3>Conclusion</h3><p>BERT’s ability to understand context by reading text bidirectionally makes it a perfect candidate for tackling complex NLP tasks like Named Entity Recognition. By fine-tuning BERT on domain-specific data — such as bank transaction SMS messages — you can create powerful models that accurately extract critical information. This not only aids in better decision-making but also helps automate processes in financial services.</p><p>This blog has walked you through the essentials of BERT, its architecture, and a high-level overview of implementing BERT for NER. While the steps provide a solid roadmap, remember that real-world application requires careful data preparation, thoughtful model fine-tuning, and rigorous evaluation to achieve top-notch performance.</p><h3>References</h3><ul><li>Devlin, J., Chang, M.-W., Lee, K., &amp; Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. arXiv preprint arXiv:1810.04805.</li><li>Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., … &amp; Polosukhin, I. (2017). Attention is all you need. Advances in Neural Information Processing Systems, 30.</li><li>Hugging Face Transformers Documentation: <a href="https://huggingface.co/transformers/">https://huggingface.co/transformers/</a></li></ul><p>And there you have it — a comprehensive guide to understanding and implementing BERT for NER, complete with both conceptual insights and practical steps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=993883a1127f" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/bert-for-ner-extracting-key-information-from-bank-sms-993883a1127f">BERT for NER: Extracting Key Information from Bank SMS</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning LLMs: A Practical Guide to Summarizing Conversations with Python]]></title>
            <link>https://blog.gopenai.com/fine-tuning-llms-a-practical-guide-to-summarizing-conversations-with-python-a1c1688aaecf?source=rss-fa05ca8ae5a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1c1688aaecf</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[text-summarization]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Maanjunath S Naragund]]></dc:creator>
            <pubDate>Sat, 18 May 2024 21:33:13 GMT</pubDate>
            <atom:updated>2024-05-21T13:15:21.147Z</atom:updated>
            <content:encoded><![CDATA[<h4>In today’s world of massive data, summarizing long conversations is a big challenge. Whether it’s customer service chats, meeting notes, or chatbot conversations, creating short and accurate summaries helps us understand large amounts of text. Fine-tuning pre-trained language models can solve this problem. This blog post will show you how to fine-tune a language model for summarizing dialogues using Python.</h4><p>In the past year and a half, natural language processing (NLP) has changed a lot because of Large Language Models (LLMs). These models can do things with language that seemed impossible just a few years ago.</p><p>LLMs are amazing — they can translate languages, analyze sentiments, and even generate text. But training these models from scratch is very expensive and takes a lot of time. That’s why fine-tuning is so important. Fine-tuning means taking a pre-trained model and adapting it to perform specific tasks. This makes the model better at those tasks and useful in more situations.</p><p>With fine-tuning, we can use the powerful abilities of pre-trained LLMs and train them to do exactly what we need. This makes them incredibly useful for things like customer service chatbots, research tools, and more.</p><p>We will leverage several advanced libraries and tools from the Hugging Face ecosystem, including transformers, datasets, peft, and bitsandbytes. These tools are designed to handle various aspects of natural language processing (NLP) tasks efficiently, from loading and preprocessing datasets to configuring and training sophisticated models. Here&#39;s an overview of what we will cover:</p><ol><li><strong>Installing Required Packages:</strong> We’ll start by installing all the necessary Python packages.</li><li><strong>Importing Necessary Libraries:</strong> Next, we’ll import the essential libraries that will be used throughout the fine-tuning process.</li><li><strong>Loading Dataset: </strong>We will load the dialogsum dataset.</li><li><strong>Preparing and Preprocessing the Dataset:</strong> We will prepare it for training by defining and applying a prompt template. Preprocess the dataset by tokenizing the text and removing unnecessary columns.</li><li><strong>Configuring and Loading the Model:</strong> We’ll configure and load the pre-trained language model using BitsAndBytesConfig for efficient memory usage.</li><li><strong>Configuring and Initializing QLoRA: </strong>We’ll set up QLoRA (Quantized LoRA) parameters to enable parameter-efficient fine-tuning.</li><li><strong>Setting Up Training Arguments:</strong> We will define and set the training arguments, including the batch size, learning rate, and evaluation strategy.</li><li><strong>Saving and Loading the Trained Model:</strong> Post training, we will save the fine-tuned model and tokenizer, and reload the model for evaluation.</li><li><strong>Testing and Evaluating the Model: </strong>Finally, we’ll test and evaluate the model’s performance using the Rouge score, a standard metric for summarization tasks.</li></ol><p>By the end of this tutorial, you’ll have a solid understanding of how to fine-tune a language model for summarizing dialogues. Let’s dive in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHB99bcD3AlFBxHFZQIAPA.png" /><figcaption>Image from DeepLearning.AI and Coursera</figcaption></figure><h3>Installing Required Packages</h3><p>Before we begin, we need to install the necessary packages. These include libraries for handling datasets, implementing transformers, parameter-efficient fine-tuning (PEFT), and evaluating model performance.</p><pre>!pip install bitsandbytes transformers peft accelerate datasets evaluate rouge_score</pre><h3>Importing Necessary Libraries</h3><p>Next, we import all the required libraries for data processing, model training, and evaluation.</p><pre>from datasets import load_dataset<br>from transformers import (AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TrainingArguments, Trainer, GenerationConfig, pipeline)<br>from tqdm import tqdm<br>from peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training<br>import torch<br>import time<br>import pandas as pd<br>import numpy as np<br>from huggingface_hub import interpreter_login<br>import os<br>import transformers</pre><h3>Loading Dataset</h3><p>We will use the dialogsum dataset for this task. First, we load the dataset. The dialogsum dataset is sourced from the Hugging Face Datasets library, which is a repository of various datasets for natural language processing tasks.</p><pre>dataset = load_dataset(&quot;knkarthick/dialogsum&quot;)</pre><h3>Preparing and Preprocessing the Dataset</h3><p>The prepare_prompt_template function formats prompts for dialogue summarization tasks by combining dialogue, instructions, and summaries. It utilizes predefined tags and constants to structure the prompts effectively. Examples from the dataset are processed using this function to generate prompts for both training and testing datasets.</p><pre><br>def prepare_prompt_template(example):<br>    dialogue = example[&#39;dialogue&#39;]<br>    summary = example[&#39;summary&#39;]<br>    <br>    PROMPT_START = &#39;&lt;s&gt;&#39;<br>    PROMPT_END = &#39;&lt;/s&gt;&#39;<br>    INTRO_BLURB = &quot;Below is an instruction that describes a task. Write a response that appropriately completes the request.&quot;<br>    INSTRUCTION_KEY_START = &quot;[INST]: Summarize the conversation in two lines.\n&quot;<br>    INSTRUCTION_END_KEY = &quot;[/INST]&quot;<br>    SYSTEM_START_KEY = &#39;&lt;&lt;SYS&gt;&gt;&#39;<br>    SYSTEM_END_KEY = &#39;&lt;&lt;/SYS&gt;&gt;&#39;<br>    <br>    formatted_prompt = f&#39;{PROMPT_START}{INSTRUCTION_KEY_START} {dialogue} {INSTRUCTION_END_KEY} {summary} {PROMPT_END}&#39;<br>    <br>    example[&quot;text&quot;] = formatted_prompt<br>    return example<br><br>example = dataset[&#39;train&#39;][10]<br>example = prepare_prompt_template(example)<br>print(example[&#39;text&#39;])<br><br>train_dataset = dataset[&#39;train&#39;].map(prepare_prompt_template)<br>test_dataset = dataset[&#39;test&#39;]</pre><h3>Configuring and Loading the Model</h3><p>We configure and load the pre-trained model using the BitsAndBytesConfig for efficient memory usage.</p><p>The provided code snippet configures quantization settings for a language model and initializes a pre-trained model with these settings. It sets parameters such as the precision of quantization, the type of quantization, and whether nested quantization is used. These settings are applied to a base language model obtained from the Hugging Face Model Hub. Additionally, caching is disabled in the model configuration, and a pretraining task parameter is set.</p><pre>use_4bit = True<br>bnb_4bit_compute_dtype = &quot;bfloat16&quot;<br>bnb_4bit_quant_type = &quot;nf4&quot;<br>use_nested_quant = False<br><br>compute_dtype = getattr(torch, bnb_4bit_compute_dtype)<br><br>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=use_4bit, <br>    bnb_4bit_quant_type=bnb_4bit_quant_type, <br>    bnb_4bit_compute_dtype=compute_dtype, <br>    bnb_4bit_use_double_quant=use_nested_quant<br>)<br><br>model_name = &quot;NousResearch/Llama-2-7b-chat-hf&quot;<br>device_map = &#39;auto&#39;<br><br>base_model = AutoModelForCausalLM.from_pretrained(<br>    model_name,<br>    quantization_config=bnb_config,<br>    device_map=device_map<br>)<br><br>base_model.config.use_cache = False<br>base_model.config.pretraining_tp = 1</pre><ol><li>use_4bit: A boolean variable indicating whether 4-bit precision quantization should be used. When set to True, it enables 4-bit quantization, which reduces the model&#39;s memory footprint and computational requirements while maintaining performance.</li><li>bnb_4bit_compute_dtype: A string specifying the data type used for computations during 4-bit quantization. In this case, it is set to &quot;bfloat16&quot;, which stands for &quot;bfloat16&quot; data type. Bfloat16 is a 16-bit floating-point representation that offers a compromise between precision and memory efficiency.</li><li>bnb_4bit_quant_type: A string specifying the type of quantization used for 4-bit quantization. Here, it is set to &quot;nf4&quot;, which stands for &quot;NearFloat4&quot;. NearFloat4 quantization is a method that quantizes model parameters to 4 bits while minimizing the loss in performance.</li><li>use_nested_quant: A boolean variable indicating whether nested quantization should be used. When set to True, it enables nested quantization, which applies additional quantization to certain layers or components of the model.</li><li>compute_dtype: A variable representing the data type used for computations during quantization. It is obtained using the getattr function, which retrieves an attribute (&quot;bfloat16&quot;) from the torch module.</li></ol><h3>Configuring and Initializing QLoRA</h3><p>We set up QLoRA (Quantized LoRA) parameters for fine-tuning.</p><p>PEFT (Parameter Efficient Fine-Tuning) is a method that fine-tunes large language models by updating a small subset of parameters, making it resource-efficient. QLoRA (Quantized LoRA) combines quantization with LoRA (Low-Rank Adaptation) to further reduce memory and computation requirements during fine-tuning.</p><p>This code snippet is configuring and initializing a PEFT (Parameter Efficient Fine-Tuning) model with specific settings. Let’s break it down:</p><pre>lora_r = 8<br>lora_alpha = 16<br>lora_dropout = 0.05<br><br>peft_config = LoraConfig(<br>    lora_alpha=lora_alpha,<br>    lora_dropout=lora_dropout,<br>    r=lora_r,<br>    bias=&quot;none&quot;,<br>    task_type=&quot;CAUSAL_LM&quot;,<br>)<br><br>peft_model = get_peft_model(base_model, peft_config)<br>peft_model.config.use_cache = False</pre><p>lora_r, lora_alpha, and lora_dropout: These variables define parameters for the QLoRA (Quantized LoRA) configuration.</p><ul><li>lora_r specifies the LoRA attention dimension.</li><li>lora_alpha sets the alpha parameter for LoRA scaling.</li><li>lora_dropout defines the dropout probability for LoRA layers.</li><li>task_type is set to &quot;CAUSAL_LM&quot;, specifying the type of task the model will be used for (causal language modeling).</li><li>peft_model: This variable initializes the PEFT model using the get_peft_model function.</li><li>peft_config is passed as the configuration for the PEFT model.</li></ul><p>peft_model.config.use_cache = False: This line disables caching in the model configuration, which can help save memory during training.</p><p>Overall, this code sets up a PEFT model for fine-tuning, configuring it with specific parameters for QLoRA attention and then initializing the model for further training.</p><h3>Setting Up Training Arguments</h3><p>We define the training arguments, including the output directory, batch size, learning rate, and evaluation strategy.</p><pre>output_dir = f&#39;./peft-dialogue-summary-training-{str(int(time.time()))}&#39;<br><br>training_arguments = TrainingArguments(<br>    output_dir=output_dir,<br>    warmup_steps=1,<br>    per_device_train_batch_size=1,<br>    gradient_accumulation_steps=4,<br>    max_steps=10,<br>    learning_rate=2e-4,<br>    optim=&quot;paged_adamw_8bit&quot;,<br>    logging_steps=25,<br>    logging_dir=&quot;./logs&quot;,<br>    save_strategy=&quot;steps&quot;,<br>    save_steps=25,<br>    evaluation_strategy=&quot;steps&quot;,<br>    eval_steps=25,<br>    do_eval=True,<br>    report_to=&quot;tensorboard&quot;,<br>    overwrite_output_dir=True,<br>    group_by_length=True,<br>)<br><br>trainer = transformers.Trainer(<br>    model=peft_model,<br>    train_dataset=train_dataset,<br>    eval_dataset=test_dataset,<br>    args=training_arguments,<br>    data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),<br>)<br><br>trainer.train()</pre><p>This code snippet sets up and initiates the training of a PEFT model using Hugging Face’s transformers library. Here&#39;s a brief explanation:</p><ol><li>Output Directory:</li></ol><ul><li>output_dir = f&#39;./peft-dialogue-summary-training-{str(int(time.time()))}&#39;: Creates a unique directory to store training outputs based on the current timestamp.</li></ul><p>2. Training Arguments:</p><ul><li>output_dir: Where to save model checkpoints.</li><li>warmup_steps: Number of warmup steps.</li><li>per_device_train_batch_size: Batch size per device.</li><li>gradient_accumulation_steps: Number of steps to accumulate gradients.</li><li>max_steps: Maximum number of training steps.</li><li>learning_rate: Learning rate.</li><li>optim: Optimizer type, here it&#39;s &quot;paged_adamw_8bit&quot;.</li><li>logging_steps: Frequency of logging.</li><li>logging_dir: Directory for log files.</li><li>save_strategy and save_steps: Strategy and frequency for saving checkpoints.</li><li>evaluation_strategy and eval_steps: Strategy and frequency for evaluation.</li><li>do_eval: Whether to perform evaluation during training.</li><li>report_to: Reporting to &quot;tensorboard&quot; for logging.</li><li>overwrite_output_dir: Whether to overwrite the output directory.</li><li>group_by_length: Whether to group sequences of similar lengths for efficient training.</li></ul><p>3. Trainer Initialization:</p><ul><li>model: The PEFT model to be trained.</li><li>train_dataset and eval_dataset: Training and evaluation datasets.</li><li>data_collator: A data collator for language modeling that handles batching and padding.</li></ul><p>4. Model Training:</p><ul><li>trainer.train(): Starts the training process based on the specified settings.</li></ul><h3>Test and Evaluating the Model</h3><p>Finally, we evaluate the model’s performance using the Rouge score.</p><p>Prepare prompt for testing using following code snippet.</p><pre>def prepare_test_prompt_template(example):<br>    dialogue = example[&#39;dialogue&#39;]<br>    summary = example[&#39;summary&#39;]<br>    <br>    PROMPT_START = &#39;&lt;s&gt;&#39;<br>    INSTRUCTION_KEY_START = &quot;[INST]: Summarize the conversation in one line.\n&quot;<br>    INSTRUCTION_END_KEY = &quot;[/INST]&quot;<br>    <br>    formatted_prompt = f&#39;{PROMPT_START}{INSTRUCTION_KEY_START} {dialogue} {INSTRUCTION_END_KEY}&#39;<br>    return formatted_prompt, summary<br><br>index = 0<br>example = test_dataset[index]<br><br>prompt, summary = prepare_test_prompt_template(example)<br>input_ids = tokenizer(prompt, return_tensors=&#39;pt&#39;).input_ids<br><br>peft_model_outputs = peft_model.generate(input_ids=input_ids, generation_config=GenerationConfig(max_new_tokens=200, num_beams=1))<br>peft_model_text_output = tokenizer.decode(peft_model_outputs[0], skip_special_tokens=True)</pre><pre>import evaluate<br><br># Load the Rouge evaluator<br>rouge = evaluate.load(&#39;rouge&#39;)<br><br># Compute ROUGE scores for the generated summaries compared to the human summaries<br>rouge.compute(<br>    predictions=generated_output,<br>    references=human_summary,<br>    use_aggregator=True,<br>    use_stemmer=True<br>)</pre><ul><li>rouge = evaluate.load(&#39;rouge&#39;): Loads the ROUGE evaluator, which is commonly used for summarization tasks to measure the overlap between the generated summaries and reference summaries.</li><li>rouge.compute(...): Computes the ROUGE scores using the generated summaries and the human reference summaries.</li></ul><p>ROUGE (Recall-Oriented Understudy for Gisting Evaluation) is a set of metrics used to evaluate the quality of text summarization and translation by comparing the generated text to a reference text.</p><p>Here are the main ROUGE metrics:</p><ol><li>ROUGE-N: Measures the overlap of n-grams (e.g., ROUGE-1 for unigrams, ROUGE-2 for bigrams) between the generated and reference texts.</li><li>ROUGE-L: Measures the longest common subsequence (LCS) of words, considering word order.</li><li>ROUGE-S: Measures the overlap of skip-bigrams, allowing gaps between words.</li><li>ROUGE-SU: Combines skip-bigrams with unigram overlap for a more comprehensive measure.</li></ol><p>These metrics help assess how closely the generated text matches human-written summaries, considering both recall and precision.</p><h3>Conclusion</h3><p>Over the past year and a half, the field of natural language processing (NLP) has seen significant advancements thanks to the rise of Large Language Models (LLMs). These models have revolutionized applications like language translation, sentiment analysis, and text generation. Despite their impressive capabilities, training LLMs from scratch remains a time-consuming and expensive process. This is where fine-tuning pre-trained models comes into play.</p><p>In this blog, we explored how to fine-tune a pre-trained language model using the DialogSum dataset to generate concise and accurate dialogue summaries. We covered essential steps, from preparing data and configuring models with techniques like PEFT and QLoRA to evaluating the model’s performance using ROUGE metrics.</p><p>Fine-tuning enhances the model’s ability to perform specialized tasks, making advanced NLP accessible and applicable across various domains. By leveraging pre-trained models and fine-tuning them for specific purposes, we can create powerful, efficient solutions that fit to our needs.</p><p>As we continue to explore and innovate in the field of NLP, the potential for developing advanced AI systems that can understand and process human language more effectively grows. Embrace the journey of fine-tuning language models and unlock the full potential of your NLP applications. Happy fine-tuning!</p><p><strong>References</strong></p><ul><li>For comprehensive courses on deep learning and natural language processing, explore offerings from <a href="https://www.deeplearning.ai/">deeplearning.ai</a> on <a href="https://www.coursera.org/">Coursera</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1c1688aaecf" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/fine-tuning-llms-a-practical-guide-to-summarizing-conversations-with-python-a1c1688aaecf">Fine-Tuning LLMs: A Practical Guide to Summarizing Conversations with Python</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Image Quality: Exploring SRGAN for Super-Resolution]]></title>
            <link>https://blog.gopenai.com/enhancing-image-quality-exploring-srgan-for-super-resolution-8a6fadc2f248?source=rss-fa05ca8ae5a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a6fadc2f248</guid>
            <category><![CDATA[image-enhancement]]></category>
            <category><![CDATA[image-super-resolution]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[srgan]]></category>
            <dc:creator><![CDATA[Maanjunath S Naragund]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 13:40:45 GMT</pubDate>
            <atom:updated>2024-04-09T10:13:17.037Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Low to High: Exploring SRGAN for Image Enhancement</h3><h3><strong>Introduction</strong></h3><p>In the realm of computer vision, achieving high-resolution images from their low-resolution counterparts has always been a pivotal task. The advent of Super-Resolution Generative Adversarial Networks (SRGANs) has revolutionized this domain. SRGANs, powered by deep learning, have gained significant traction due to their ability to generate realistic high-resolution images from low-resolution inputs. In this blog post, we’ll delve into the workings of SRGANs, their applications in today’s world, and explore a practical implementation using TensorFlow and Keras.</p><h4><strong>Understanding SRGANs</strong></h4><p>Super-Resolution Generative Adversarial Networks (SRGANs) are a type of Generative Adversarial Network (GAN) specifically tailored for super-resolution tasks. Unlike traditional interpolation techniques, SRGANs leverage deep neural networks to learn complex mappings between low-resolution and high-resolution image spaces. They consist of two primary components: the generator and the discriminator.</p><ul><li><strong>Generator: </strong>The generator network takes low-resolution images as input and produces high-resolution images as output. It employs a series of convolutional layers, residual blocks, and upsampling layers to enhance the image resolution while preserving important features.</li><li><strong>Discriminator:</strong> The discriminator network, akin to a binary classifier, distinguishes between real high-resolution images and fake high-resolution images generated by the generator. It helps in training the generator by providing feedback on the realism of generated images.</li></ul><h4><strong>Applications of SRGANs</strong></h4><p>The applications of SRGANs are widespread across various domains:</p><ul><li><strong>Enhanced Visual Quality: </strong>SRGANs can be used to enhance the visual quality of images in applications like image editing, photography, and content creation.</li><li><strong>Medical Imaging:</strong> In the field of medical imaging, SRGANs aid in enhancing the resolution of medical scans, enabling better diagnosis and analysis.</li><li><strong>Satellite Imaging:</strong> SRGANs play a crucial role in enhancing satellite images, providing clearer and more detailed insights for applications like urban planning, agriculture, and disaster management.</li><li><strong>Surveillance Systems: </strong>High-resolution surveillance footage is essential for accurate monitoring and analysis. SRGANs can improve the quality of surveillance images, aiding in better identification and tracking.</li></ul><h4><strong>Implementing SRGAN with TensorFlow</strong></h4><p>Let’s walk through a practical implementation of SRGAN using TensorFlow. We’ll cover key steps involved in the process:</p><p><strong>Data Preparation:</strong></p><p>We fetch a dataset containing high-resolution images. and convert to low-resolution of size (64,64,3) and high-resolution image of size(256,256,3) pairs and preprocess them for training.</p><pre>IN_IMAGE_SIZE = 64<br>OUT_IMAGE_SIZE = 256<br><br>BATCH_SIZE = 16<br><br>def preprocess_image(image, isInput=True):<br>    # Decode JPEG image with 3 color channels<br>    image = tf.io.decode_jpeg(image, channels=3)<br>    <br>    # Resize image based on input or output size<br>    if isInput:<br>        image = tf.image.resize(image, [IN_IMAGE_SIZE, IN_IMAGE_SIZE])<br>    else:<br>        image = tf.image.resize(image, [OUT_IMAGE_SIZE, OUT_IMAGE_SIZE])<br>    <br>    # Normalize image to [0,1] range<br>    image /= 255.0<br>    <br>    # Cast image to float16 dtype<br>    image = tf.cast(image, dtype=tf.float16)<br>    return image<br><br>def load_preprocess_image(path, isInput):<br>    # Read image file<br>    image = tf.io.read_file(path)<br>    # Preprocess image<br>    return preprocess_image(image, isInput)<br><br>def load_preprocess_from_image_path(in_path, out_path):<br>    # Load and preprocess input and output images<br>    return load_preprocess_image(in_path, isInput=True), load_preprocess_image(out_path, isInput=False)<br><br># Create tf.data.Dataset from image paths<br>ds = tf.data.Dataset.from_tensor_slices((x_train, y_train))<br><br># Map preprocessing function to the dataset<br>ds = ds.map(load_preprocess_from_image_path)<br><br># Shuffle dataset with buffer size equal to dataset length<br>ds = ds.shuffle(buffer_size=len(x_train))<br><br># Repeat dataset indefinitely<br>ds = ds.repeat()<br><br># Batch dataset with specified batch size<br>ds = ds.batch(BATCH_SIZE)<br><br># Prefetch dataset to optimize performance<br>ds = ds.prefetch(buffer_size=tf.data.AUTOTUNE)</pre><p>This code defines a preprocessing pipeline using tf.data.Dataset for loading, preprocessing, shuffling, batching, and prefetching images from file paths.</p><p><strong>Model Building:</strong></p><p>We define the architecture of the generator and discriminator networks. The generator aims to generate realistic high-resolution images, while the discriminator distinguishes between real and generated images.</p><ul><li><strong>Generator and Discriminator</strong></li></ul><pre># Define the Generator model<br>class Generator(Model):<br>    def __init__(self, res_range, up_range):<br>        super(Generator, self).__init__()<br>        # Initial number of filters for the convolutional layers<br>        self.initial_filters = 64<br>        <br>        # Convolutional layer to process input images<br>        self.cn1 = keras.layers.Conv2D(self.initial_filters, kernel_size=3, strides=1, padding=&#39;same&#39;)<br>        # Parametric ReLU activation<br>        self.prl1 = keras.layers.PReLU()<br>        <br>        # List to store residual blocks<br>        self.res_blocks = [ResidualBlock(self.initial_filters) for _ in range(res_range)]<br>        <br>        # List to store upsample blocks<br>        self.up_blocks = [UpsampleBlock(self.initial_filters * i) for i in range(1, up_range + 1)]<br>        <br>        # Convolutional layer for output image generation<br>        self.out = keras.layers.Conv2D(3, 3, padding=&#39;same&#39;)<br><br>    def call(self, inputs):<br>        # First convolutional layer followed by activation<br>        x = self.cn1(inputs)<br>        x = self.prl1(x)<br>        <br>        # Apply residual blocks<br>        for block in self.res_blocks:<br>            x = block(x)<br>        <br>        # Apply upsample blocks<br>        for block in self.up_blocks:<br>            x = block(x)<br>        <br>        # Final convolutional layer for output image generation<br>        out = self.out(x)<br>        return out<br><br>    def summary(self, input_s):<br>        # Define input shape and print model summary<br>        x = keras.Input(shape=input_s)<br>        return keras.Model(inputs=[x], outputs=self.call(x)).summary()<br><br><br># Define the Discriminator model<br>class Discriminator(Model):<br>    def __init__(self):<br>        super(Discriminator, self).__init__()<br>        # Initial number of filters for the convolutional layers<br>        self.filters = 64<br>        <br>        # Convolutional layer to process input images<br>        self.cn = keras.layers.Conv2D(self.filters, kernel_size=3, padding=&#39;same&#39;)<br>        # Max pooling layer<br>        self.mp = keras.layers.MaxPooling2D()<br>        # Leaky ReLU activation<br>        self.lr = keras.layers.LeakyReLU(alpha=0.2)<br>        <br>        # List to store downsample blocks<br>        self.ds_blocks = [DownsampleBlock(self.filters * i) for i in range(2, 6)]<br>        <br>        # Flatten layer<br>        self.fn = keras.layers.Flatten()<br>        # Dense layer<br>        self.dl = keras.layers.Dense(1024)<br>        # Leaky ReLU activation<br>        self.lr = keras.layers.LeakyReLU(alpha=0.2)<br>        # Dropout layer for regularization<br>        self.dp = keras.layers.Dropout(0.5)<br>        # Output layer with sigmoid activation<br>        self.out = keras.layers.Dense(1, activation=&#39;sigmoid&#39;)<br>        <br>    def call(self, inputs):<br>        # Convolutional layer followed by activation and max pooling<br>        x = self.cn(inputs)<br>        x = self.lr(x)<br>        x = self.mp(x)<br>        <br>        # Apply downsample blocks<br>        for block in self.ds_blocks:<br>            x = block(x)<br>        <br>        # Flatten, apply dense layers, and dropout<br>        x = self.fn(x)<br>        x = self.dl(x)<br>        x = self.lr(x)<br>        x = self.dp(x)<br>        <br>        # Output layer for binary classification<br>        out = self.out(x)<br>        return out<br><br>    def summary(self, input_s):<br>        # Define input shape and print model summary<br>        x = keras.Input(shape=input_s)<br>        return keras.Model(inputs=x, outputs=self.call(x)).summary()</pre><ul><li><strong>Loss Function: </strong>We employ a VGG19-based <em>perceptual loss</em> function to measure the difference between generated and ground truth images. The VGGPerceptualLoss class is defined to compute the perceptual loss between two images based on their feature representations extracted from a pre-trained VGG19 model. The mean squared error (MSE) between the extracted features of the input images is computed using keras.losses.MeanSquaredError() and returned as the perceptual loss.</li></ul><pre># Define VGGPerceptualLoss class for perceptual loss computation<br>class VGGPerceptualLoss(Model):<br>    def __init__(self):<br>        super(VGGPerceptualLoss, self).__init__()<br>        # Load pre-trained VGG19 model without top layers<br>        vgg_model = keras.applications.vgg19.VGG19(include_top=False, input_shape=(OUT_IMAGE_SIZE, OUT_IMAGE_SIZE, 3))<br>        <br>        # Create a sub-model with only a portion of the VGG19 model<br>        self.vgg_model = keras.models.Model(inputs=vgg_model.inputs, outputs=vgg_model.layers[10].output)<br>        <br>        # Freeze the weights of the VGG19 model to prevent training<br>        self.vgg_model.trainable = False<br><br>    def call(self, x, y):<br>        # Preprocess input images for VGG19 model<br>        x = keras.applications.vgg19.preprocess_input(x)<br>        y = keras.applications.vgg19.preprocess_input(y)<br>        <br>        ...<br>        <br>        # Compute mean squared error between extracted features<br>        return keras.losses.MeanSquaredError()(features_x, features_y)</pre><ul><li><strong>Training:</strong> We train the SRGAN model using the prepared dataset, optimizing both the generator and discriminator networks. And the current model is trained on one epoch.</li></ul><pre># Define SRGAN (Super-Resolution Generative Adversarial Network) model<br>class SRGAN(Model):<br>    def __init__(self, generator, discriminator, perceptual_loss):<br>        super(SRGAN, self).__init__()<br>        # Initialize generator, discriminator, and perceptual loss components<br>        self.generator = generator<br>        self.discriminator = discriminator<br>        self.perceptual_loss = perceptual_loss<br>        <br>    def compile(self, gen_opt, desc_opt):<br>        # Compile the SRGAN model with specified optimizers<br>        super(SRGAN, self).compile()<br>        # Set generator and discriminator optimizers<br>        self.gen_opt = gen_opt<br>        self.desc_opt = desc_opt<br>        <br>    def train_step(self, data):<br>        # Define training step for SRGAN model<br>        lr_images, hr_images = data<br>        <br>        ...<br><br>        # Return dictionary containing generator and discriminator losses<br>        return {&#39;gen_loss&#39;: gen_loss, &#39;disc_loss&#39;: total_disc_loss}<br><br># Instantiate Generator, Discriminator, and VGGPerceptualLoss objects<br>generator = Generator(res_range=3, up_range=2)  # Generator model with 3 residual blocks and 2 upsampling blocks<br>discriminator = Discriminator()  # Discriminator model<br>vgg_loss = VGGPerceptualLoss()  # Perceptual loss model based on VGG19 features<br><br># Instantiate SRGAN (Super-Resolution Generative Adversarial Network) model with the defined components<br>srgan = SRGAN(generator, discriminator, vgg_loss)<br><br># Define Adam optimizers for generator and discriminator<br>gen_opt = keras.optimizers.Adam()  # Optimizer for generator<br>disc_opt = keras.optimizers.Adam()  # Optimizer for discriminator<br><br># Compile SRGAN model with the specified optimizers<br>srgan.compile(gen_opt, disc_opt)</pre><ul><li>The SRGAN class represents the Super-Resolution Generative Adversarial Network model, which consists of a generator, a discriminator, and a perceptual loss component.</li><li>In the constructor __init__, the <em>generator, discriminator, and perceptual loss</em> components are initialized and stored as attributes of the SRGAN model.</li><li>The compile method is overridden to specify the optimizers for training the generator and discriminator.</li><li>The train_step method defines a single training step for the SRGAN model. It takes a batch of low-resolution (lr_images) and high-resolution (hr_images) image pairs as input.</li><li>Within the training step, the generator produces super-resolution images (sr_images) from low-resolution inputs.</li><li>The discriminator computes outputs for both real and generated images and calculates <em>binary crossentropy losses</em>.</li><li>The perceptual loss between high-resolution and super-resolution images is computed using the specified perceptual loss function.</li><li>Gradients of the generator and discriminator losses are computed using gradient tape, and the optimizer is used to update the model weights.</li><li>Finally, a dictionary containing generator and discriminator losses is returned from the training step.</li><li>The code instantiates the components needed for training the SRGAN model: Generator, Discriminator, and VGGPerceptualLoss.</li><li>The Generator is created with 3 residual blocks and 2 upsampling blocks, specified by the parameters res_range and up_range.</li><li>The Discriminator is initialized without any custom parameters.</li><li>VGGPerceptualLoss is instantiated to compute the perceptual loss between high-resolution and super-resolution images based on VGG19 features.</li><li>The SRGAN model is then instantiated with the previously defined Generator, Discriminator, and VGGPerceptualLoss objects.</li><li>Adam optimizers are defined for both the generator and discriminator.</li><li>Finally, the SRGAN model is compiled with the specified Adam optimizers, allowing it to be trained using the Adam optimization algorithm.</li></ul><p><strong>Testing:</strong> Save the model and we validate the trained SRGAN model by generating high-resolution images from low-resolution inputs and comparing them with ground truth images.</p><pre># Save the model<br>generator.save(&#39;srgan_epoch_1.h5&#39;)<br><br># Import tqdm library for progress bar visualization<br>from tqdm import tqdm<br><br># Define validation function for evaluating the model performance<br>def validation(x_test, y_test):<br>    i = 0  # Initialize counter for images displayed<br>    for x, y in tqdm(zip(x_test, y_test)):  # Iterate through test image pairs with tqdm progress bar<br>        rand_int = np.random.randint(len(x_test))  # Generate random index for selecting a test image pair<br>        x = x_test[rand_int]  # Get low-resolution image path<br>        y = y_test[rand_int]  # Get high-resolution image path<br>        <br>        # Display low-resolution, high-resolution, and super-resolution images<br>        plt.figure(figsize=(12, 6))  # Set figure size<br>        plt.subplot(131)  # Subplot for low-resolution image<br>        plt.title(&#39;Low resolution image&#39;)  # Set title for subplot<br>        in_img = load_image(x, True)  # Load and preprocess low-resolution image<br>        in_img = cv2.resize(in_img, (IN_IMAGE_SIZE, IN_IMAGE_SIZE))  # Resize low-resolution image<br>        in_img = img / 255.  # Normalize image values<br>        plt.imshow(in_img)  # Display low-resolution image<br>        <br>        plt.subplot(132)  # Subplot for high-resolution image<br>        plt.title(&#39;High resolution image&#39;)  # Set title for subplot<br>        y_img = load_image(y, True)  # Load and preprocess high-resolution image<br>        y_img = cv2.resize(y_img, (OUT_IMAGE_SIZE, OUT_IMAGE_SIZE))  # Resize high-resolution image<br>        plt.imshow(y_img)  # Display high-resolution image<br>        <br>        plt.subplot(133)  # Subplot for super-resolution image<br>        plt.title(&#39;SRGAN generated image&#39;)  # Set title for subplot<br>        in_img = np.array(in_img, dtype=np.float16)  # Convert low-resolution image to numpy array<br>        in_img = np.array([in_img])  # Add batch dimension to image<br>        gen_image = generator.predict(in_img)  # Generate super-resolution image using the trained generator<br>        gen_image = gen_image[0]  # Extract generated image from batch<br>        gen_image = (gen_image * 255).astype(&#39;int&#39;) # Convert image to uint8 data type<br>        plt.imshow(gen_image)  # Display super-resolution image<br>        i += 1  # Increment image counter<br>        if i &gt;= 1:  # Break the loop after displaying one image pair<br>            break</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*jAZWxsbzQJnJw4VdL5sO3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*qq8zz4SOp2qBva2I_oKsZw.png" /></figure><h4><strong>Conclusion:</strong></h4><p>Super-Resolution Generative Adversarial Networks (SRGANs) offer a powerful solution for enhancing image resolution in various applications. With advancements in deep learning and frameworks like TensorFlow. SRGANs continue to evolve, enabling the generation of high-quality images with unprecedented realism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a6fadc2f248" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/enhancing-image-quality-exploring-srgan-for-super-resolution-8a6fadc2f248">Enhancing Image Quality: Exploring SRGAN for Super-Resolution</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide to Implementing Retrieval Augmented Generation in Python]]></title>
            <link>https://blog.gopenai.com/step-by-step-guide-to-implementing-retrieval-augmented-generation-in-python-4801be2771c3?source=rss-fa05ca8ae5a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4801be2771c3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Maanjunath S Naragund]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 16:16:05 GMT</pubDate>
            <atom:updated>2024-02-29T09:35:50.857Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we’ll embark on a journey through a Python script that orchestrates a Conversational AI ecosystem using the LangChain library and OpenAI. This code sets the stage for an intelligent system capable of answering user queries by integrating document retrieval and generative language models. <a href="https://github.com/imanjunathn/LangChain_OpenAi">Git link</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*ys44J6jLm5vSTjFIMDDEfw.png" /><figcaption>High-level overview of the Retrieval Augmented Generation System. Image by author. Icons from <a href="https://www.flaticon.com/">Flaticons</a>.</figcaption></figure><h3>Introduction:</h3><p>In the realm of natural language processing (NLP), the integration of retrieval-based systems with powerful language models has led to the creation of advanced conversational agents. In this blog, we’ll explore the development of a Retrieval-Augmented Generation System using LangChain, a versatile NLP library, and OpenAI’s GPT model.</p><p>By combining document retrieval and generative language models. This system is designed to provide informative and contextually relevant responses to user queries.</p><h3>Setting up the Environment:</h3><p>The initial steps involve installing necessary libraries such as docarray, openai, LangChain, and others. The OpenAI API key is set up for authentication, and documents are loaded into the system. These documents, extracted from PDFs in this example, serve as the knowledge base for the retrieval system.</p><pre>! pip install docarray <br>! pip install --upgrade langchain<br>! pip install openai<br>! pip install tiktoken</pre><p>These commands ensure that the essential libraries, such as docarray, langchain, and openaiare installed.</p><pre>import os<br><br># ...<br><br># Set up OpenAI API key<br>os.environ[&#39;OPENAI_API_KEY&#39;] = &#39;&#39;<br>openai.api_key = os.environ[&#39;OPENAI_API_KEY&#39;]</pre><p>The introductory section takes care of installing essential packages and importing modules. This sets the foundation for the subsequent development of the Conversational AI ecosystem.</p><h3>Loading and Processing Document:</h3><p>To enhance the efficiency of the system, the loaded documents undergo processing, which includes splitting them into smaller chunks and removing duplicates. The text splitter is configured to handle various Markdown separators, ensuring the documents are appropriately segmented for effective retrieval.</p><pre>import openai<br>from langchain.document_loaders import PyPDFLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br><br># ...<br><br># Load documents from PDF files<br>docs = []<br># 1<br>path = &quot;/kaggle/input/python-docs&quot;<br>for file in os.listdir(path):<br>    loader = PyPDFLoader(file_path=os.path.join(path, file))<br>    docs.extend(loader.load())<br><br># ...<br># 2.<br># Splitting and processing documents<br>def split_docs(docs):<br>    # ... (existing code for document splitting)<br><br>docs_processed_unique = split_docs(docs)</pre><p>The loaded documents are then processed using a function named split_docs. This function takes the loaded documents as input and performs various operations, including splitting the documents into smaller chunks, updating metadata, and removing duplicates.</p><h3>Embeddings and Vector Database:</h3><pre>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.vectorstores import DocArrayInMemorySearch<br><br># ...<br><br># Define embedding model and vector database<br># 1<br># Embedding setup<br>embedding_model = OpenAIEmbeddings()<br><br># Vector database creation<br># 2<br>vectordb = DocArrayInMemorySearch.from_documents(documents=docs_processed_unique, embedding=embedding_model)<br># 3<br>retriever = vectordb.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 5})</pre><p>An embedding model using OpenAIEmbeddings is created, and an in-memory vector database is generated from the processed documents. A retriever is then established to perform similarity searches.</p><p>In the first line, an instance of the OpenAIEmbeddings class is created and assigned to the variable embedding_model. This class is likely responsible for transforming raw text into numerical vectors, often called embeddings. Embeddings capture semantic information about the input text, enabling the model to understand the context and meaning of words or phrases.</p><p>Next, a vector database (vectordb) is instantiated using DocArrayInMemorySearch from the LangChain library. This database is designed to store and efficiently search through the processed documents. It utilizes the embeddings generated by the previously defined embedding_model.</p><p>The from_documents method takes a list of processed documents (docs_processed_unique) and the embedding model. It creates a searchable vector database, allowing for quick retrieval of relevant documents based on similarity.</p><p>This retriever will be used to find documents that are semantically similar to a user’s query, forming an integral part of the Retrieval Augmented Generation System.</p><h3>Conversation Templates:</h3><p>Effective communication is at the heart of Conversational AI. To guide the interaction between the user and the system, templates for system and user messages are defined. These templates provide a structured foundation for generating meaningful responses.</p><p>The variable general_system_template holds a template string. This template likely defines a standard system message that is displayed to the user before receiving their input.</p><p>The variable general_user_template holds a template for user input. The template includes a placeholder {question}, suggesting that this template will be dynamically filled with the user&#39;s actual question during the conversation.</p><p>The code then creates a list named messages containing instances of SystemMessagePromptTemplate and HumanMessagePromptTemplate using the defined templates.</p><p>These message templates are then used to construct a ChatPromptTemplate named qa_cv_prompt, which likely serves as a structured template for a conversational exchange between the user and the chatbot.</p><pre># ... (previous code)<br><br>general_system_template = r&quot;&quot;&quot;<br># ... (template string)<br>&quot;&quot;&quot;<br><br>general_user_template = &quot;&quot;&quot;{question}&quot;&quot;&quot;<br><br>messages = [<br>    SystemMessagePromptTemplate.from_template(general_system_template),<br>    HumanMessagePromptTemplate.from_template(general_user_template)<br>]<br><br>qa_cv_prompt = ChatPromptTemplate.from_messages(messages)<br>qa_cv_prompt</pre><p>In essence, the “Conversation Templates” section establishes a framework for communication by defining templates for system messages and user input. These templates guide the interaction between the user and the Conversational AI system, ensuring a coherent and context-aware conversation.</p><h3>Conversational Chain Construction:</h3><p>The core of the system is a Conversational Retrieval Chain, where LangChain’s conversational model interacts with the document retriever. The retrieval process involves filtering documents based on datetime, ensuring that only relevant and appropriate information is presented.</p><p>The retrieval chain is integrated with the GPT model, creating a dynamic system capable of both retrieving and generating responses. The conversational chain is equipped with memory management, allowing it to retain context across interactions.</p><pre># Conversational chain setup<br>filtered_retriever = FilteredRetriever(vectorstore=retriever, filter_prefix=123456)<br><br># Model and chain initialization<br>llm_name = &quot;gpt-3.5-turbo-0301&quot;<br>chain_type = &#39;stuff&#39;<br>llm = ChatOpenAI(model_name=llm_name, temperature=0, max_tokens=512)<br><br>qa_chain = ConversationalRetrievalChain.from_llm(<br>    llm=llm,<br>    chain_type=chain_type,<br>    retriever=filtered_retriever,<br>    return_source_documents=True,<br>    return_generated_question=True,<br>    combine_docs_chain_kwargs={&#39;prompt&#39;: qa_cv_prompt},<br>)</pre><p>The main component, the qa_chain (Conversational Retrieval Chain), is configured using the ConversationalRetrievalChain.from_llm method. This method takes the language model (llm), the chain type (set to &#39;stuff&#39;), a retriever (filtered_retriever), and various additional parameters such as returning source documents and generated questions.</p><p>Here, the chain is configured to incorporate the language model, the filtered retriever, and memory settings. It is designed to handle conversational interactions, retrieve relevant documents, and generate responses based on the user’s queries.</p><h3>User Interaction Testing the System:</h3><p>User queries are handled through a well-defined conversational prompt, consisting of system and user message templates. The system prompt sets guidelines for generating responses, emphasizing ethical and positive content. User queries are then fed into the system, initiating the retrieval and generation process.</p><p>A testing function is implemented to demonstrate the system’s functionality. The model processes user queries, utilizing the conversational chain to retrieve and generate responses. The inference time and resulting answers are then presented</p><pre># User interaction and testing function<br>def test(model, query, ch=[]):<br>    # ... (existing code for testing)<br><br># Example user query<br>user_query = &quot;What is list comprehension in python? with example&quot;<br>query_vector = embedding_model.embed_query(user_query)<br><br># Testing the system<br>test(qa_chain, query=user_query)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4l3YskQ6J_LvrZJWn0_y5Q.png" /></figure><h3>Conclusion:</h3><p>The Retrieval-Augmented Generation System we’ve explored combines the power of document retrieval with advanced language models, resulting in a conversational agent capable of providing contextually relevant and informative responses. This system, built with LangChain and powered by OpenAI’s GPT, exemplifies the potential of integrating retrieval and generation mechanisms for enhanced natural language understanding and interaction.</p><p>By leveraging the capabilities of both retrieval and generation, developers can create sophisticated conversational agents that excel in understanding user queries and delivering coherent and meaningful responses. The synergy between LangChain and GPT opens the door to innovative applications in chatbots, virtual assistants, and information retrieval systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4801be2771c3" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/step-by-step-guide-to-implementing-retrieval-augmented-generation-in-python-4801be2771c3">Step-by-Step Guide to Implementing Retrieval Augmented Generation in Python</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Vision Transformers (ViT) with TensorFlow and Keras: A CIFAR-100 Experiment]]></title>
            <link>https://blog.gopenai.com/understanding-vision-transformers-vit-with-tensorflow-and-keras-a-cifar-100-experiment-b820e08473f8?source=rss-fa05ca8ae5a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b820e08473f8</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Maanjunath S Naragund]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 19:13:51 GMT</pubDate>
            <atom:updated>2024-03-12T16:49:17.056Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, Vision Transformers (ViT) have revolutionized the field of computer vision, providing a fresh perspective on image classification tasks. In this blog post, we’ll embark on a journey to implement a ViT model using TensorFlow and Keras, specifically tailored for classifying images from the CIFAR-100 dataset. Let’s dive into the code and explore the intricacies of building a Vision Transformer.</p><h3>Setting the Stage</h3><p>Before we delve into the code, let’s grasp some key concepts:</p><h4>Vision Transformers (ViT)</h4><p>Vision Transformers break away from traditional Convolutional Neural Networks (CNNs) by treating an entire image as a sequence of patches. This global perspective allows ViTs to capture long-range dependencies and has demonstrated remarkable performance on various computer vision tasks.</p><h4>CIFAR-100 Dataset</h4><p>The CIFAR-100 dataset consists of 60,000 32x32 color images distributed across 100 different classes, each containing 600 images. It serves as an excellent benchmark for evaluating the performance of image classification models.</p><h3>Code Walkthrough</h3><p>Let’s walk through the essential components of the code, which demonstrates how to construct a ViT model for CIFAR-100 classification:</p><pre># Import necessary libraries<br>import tensorflow as tf<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import keras<br>from keras import layers</pre><pre># ... [Data Loading and Preprocessing]</pre><pre># ... [Model Configuration]</pre><pre># ... [Data Augmentation]</pre><pre># ... [Model Architecture]</pre><pre># ... [Training and Evaluation]</pre><h3>1. Data Loading and Preprocessing</h3><p>The code initiates by loading the CIFAR-100 dataset using Keras and printing the shapes of the training and testing sets. This provides a quick overview of the dataset:</p><pre>(x_train, y_train), (x_test, y_test) = keras.datasets.cifar100.load_data()<br>print(f&quot;x_train_shape: {x_train.shape} - y_train_shape: {y_train.shape}&quot;)<br>print(f&quot;x_test_shape: {x_test.shape} - y_test_shape: {y_test.shape}&quot;)</pre><h3>2. Model Configuration</h3><p>Key parameters such as learning rate, weight decay, batch size, and image patch dimensions are configured for the ViT model:</p><pre># configure the parameters<br>learning_rate = 0.001<br>weight_decay = 0.0001<br>batch_size = 256<br>num_epochs = 10 # For real training, use num_epochs=100. 10 is a test value<br>image_size = 48 # We&#39;ll resize input images to this size<br>patch_size = 6 # Size of the patches to be extract from the input images<br>num_patches = (image_size // patch_size) ** 2<br>embed_dim = 64<br>num_heads = 8<br>transformer_layers = 3 # Size of the transformer layers block<br>transfomer_units = [<br>    embed_dim* 2,<br>    embed_dim<br>]<br>mlp_head_units = [<br>    2048,<br>    1024<br>]</pre><h3>3. Data Augmentation</h3><p>Data augmentation is crucial for training robust models. The code defines a data augmentation pipeline using Keras layers, incorporating resizing, rescaling, flips, rotations, and zoom:</p><pre># use data augmentation<br>data_augmentation = keras.Sequential(<br>    [<br>        layers.Resizing(image_size,image_size),<br>        layers.Rescaling(scale=1./255),<br>        layers.RandomFlip(&#39;horizontal&#39;),<br>        layers.RandomRotation(factor=0.02),<br>        layers.RandomZoom(height_factor=0.2, width_factor=0.2),<br>        layers.Normalization(),<br>    ],<br>    name=&#39;data_augmentation&#39;<br>)</pre><h3>4. Model Architecture</h3><p>The heart of the code lies in the ViT model architecture, which includes patching input images, linear projections, positional embeddings, and multiple transformer blocks:</p><pre># implement multilayer percetron<br>def mlp(x, hidden_units, dropout_rate):<br>    for units in hidden_units:<br>        x = layers.Dense(units,activation=keras.activations.gelu)(x)<br>        x = layers.Dropout(dropout_rate)(x)<br>    return x<br><br># create model<br>def vit_model(in_shape,num_classes):<br>    inputs = keras.Input(shape=in_shape)<br>    # data augmentation<br>    augmentation_layer = data_augmentation(inputs)<br>    <br>    # patching the input image into patches<br>    patching = layers.Conv2D(embed_dim, kernel_size=patch_size, strides=patch_size, padding=&#39;valid&#39;,name=&#39;patching&#39;)(augmentation_layer)<br>    patches = layers.Reshape((num_patches, embed_dim), name=&#39;pacthes&#39;)(patching)<br>    <br>    # Learnable positional embeddings<br>    position_embeddings = layers.Embedding(input_dim=num_patches, output_dim=embed_dim)(layers.Lambda(lambda x: tf.expand_dims(tf.range(num_patches), axis=0))(patches))<br><br>    # Add positional embeddings to patches<br>    patches = layers.Add()([patches,position_embeddings])<br>    <br>    # Create multiple layers of transformer block<br>    for _ in range(transformer_layers):<br>        # Create mulithead attention layer<br>        attention_output = layers.MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim // num_heads)(patches,patches)<br>        # skip connection 1<br>        x2 = layers.Add()([attention_output, patches])<br>        # Normalization 1<br>        x2 = layers.LayerNormalization(epsilon=1e-6)(x2)<br>        <br>        # Feed forward network<br>        x3 = mlp(x2, hidden_units=transfomer_units,dropout_rate=0.1)<br>        #Skip connection 2<br>        patches = layers.Add()([x3, x2])<br>        # Normalization 2<br>        patches = layers.LayerNormalization(epsilon=1e-6)(patches)<br>        <br>    representation = layers.Flatten()(patches)<br>    representation = layers.Dropout(0.5)(representation)<br>    <br>    features = mlp(representation,hidden_units=mlp_head_units,dropout_rate=0.5)<br>    # Classify output<br>    outputs = layers.Dense(num_classes, activation=&#39;softmax&#39;)(features)<br>    <br>    model = keras.models.Model(inputs=inputs, outputs=[outputs])<br>    return model</pre><pre>vit_classifier = vit_model((32,32,3),100)</pre><h3>5. Compile, train, and evaluate the model</h3><p>The run_experiment function compiles and trains the ViT model using the AdamW optimizer. Training history is then visualized, showcasing loss and top-5 accuracy over epochs. Finally, the model is evaluated on the test set:</p><pre>def run_experiment(model):<br>    optimizer = keras.optimizers.AdamW(<br>        learning_rate=learning_rate, weight_decay=weight_decay<br>    )<br><br>    model.compile(<br>        optimizer=optimizer,<br>        loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),<br>        metrics=[<br>            keras.metrics.SparseCategoricalAccuracy(name=&quot;accuracy&quot;),<br>            keras.metrics.SparseTopKCategoricalAccuracy(5, name=&quot;top-5-accuracy&quot;),<br>        ],<br>    )<br><br>    history = model.fit(<br>        x=x_train,<br>        y=y_train,<br>        batch_size=batch_size,<br>        epochs=num_epochs,<br>        validation_split=0.1<br>    )<br>    <br>    _, accuracy, top_5_accuracy = model.evaluate(x_test, y_test)<br>    print(f&quot;Test accuracy: {round(accuracy * 100, 2)}%&quot;)<br>    print(f&quot;Test top 5 accuracy: {round(top_5_accuracy * 100, 2)}%&quot;)<br><br>    return history<br><br><br>def plot_history(item):<br>    plt.plot(history.history[item], label=item)<br>    plt.plot(history.history[&quot;val_&quot; + item], label=&quot;val_&quot; + item)<br>    plt.xlabel(&quot;Epochs&quot;)<br>    plt.ylabel(item)<br>    plt.title(&quot;Train and Validation {} Over Epochs&quot;.format(item), fontsize=14)<br>    plt.legend()<br>    plt.grid()<br>    plt.show()<br><br><br>history = run_experiment(vit_classifier)<br># Visualize training history<br>plot_history(&quot;loss&quot;)<br>plot_history(&quot;top-5-accuracy&quot;)<br># Evaluate the model on the test set<br>_, accuracy, top_5_accuracy = vit_classifier.evaluate(x_test, y_test)<br>print(f&quot;Test accuracy: {round(accuracy * 100, 2)}%&quot;)<br>print(f&quot;Test top 5 accuracy: {round(top_5_accuracy * 100, 2)}%&quot;)</pre><h3>Key Considerations</h3><p>While the code provides a solid foundation, there are several considerations:</p><ul><li>Input Size: CIFAR-100 images are smaller than those typically used for ViT models. Adjustments to the model architecture and parameters may be necessary for optimal performance.</li><li>Position Embeddings: Ensure that the handling of position embeddings aligns with the original ViT architecture, often involving learnable positional embeddings.</li><li>Data Augmentation Tuning: Fine-tune data augmentation parameters based on the characteristics of CIFAR-100 images.</li></ul><h3>Conclusion</h3><p>Implementing a Vision Transformer for image classification is an exciting journey into the realm of transformer-based architectures. This code provides a starting point for experimenting with ViTs on the CIFAR-100 dataset, offering a hands-on experience in building and training these innovative models.</p><p>As you explore further, consider adjusting parameters, experimenting with different ViT variants, and applying the knowledge gained to tackle diverse computer vision tasks. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b820e08473f8" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/understanding-vision-transformers-vit-with-tensorflow-and-keras-a-cifar-100-experiment-b820e08473f8">Understanding Vision Transformers (ViT) with TensorFlow and Keras: A CIFAR-100 Experiment</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run Jupyter notebook inside Docker]]></title>
            <link>https://maanjunathn07ds.medium.com/run-jupyter-notebook-into-docker-665c5c4abda4?source=rss-fa05ca8ae5a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/665c5c4abda4</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <dc:creator><![CDATA[Maanjunath S Naragund]]></dc:creator>
            <pubDate>Sun, 18 Sep 2022 20:11:07 GMT</pubDate>
            <atom:updated>2022-09-18T20:18:56.175Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>In this article we will be learning to run Jupyter inside Docker.</strong></p><p>We come across situations many times that ML model pipeline is working in development environment but not in production environment or not seeing similar results.</p><p>The reasons might be</p><ol><li>Different python packages or dependencies versions.</li><li>Different operating systems.</li></ol><p>To avoid these kind of problems, we can use Docker.</p><h3>What is Docker?</h3><p>Docker is software platform that is designed to build, test and deploy <strong>application</strong> quickly by using <strong>Containers</strong>. Docker is being used everywhere in software development today. It is popular in DevOps and MLOps.</p><h3>What is Container?</h3><p>Containers allow developer to package and isolate applications with their entire runtime environment — all of the files necessary to run.</p><p><strong>NOTE:</strong> In this we will be using mac machine to do the example.</p><p>Steps to be followed :</p><ol><li>Download and install Docker for mac machine. Follow the installation from the bellow link <a href="https://docs.docker.com/desktop/install/mac-install/">https://docs.docker.com/desktop/install/mac-install/</a></li></ol><p>Once you open the docker desktop application you will see the following example screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1LZkNlxWIu_Nd_JESZ71Kw.png" /></figure><p>2. Open any development IDE. Here, I’m using Visual Studio.</p><p>3. Create a folder name “app”. Inside folder “app” create a file without extension and name the file as ‘Dockerfile’. And add the following lines into the file.</p><pre>FROM python:3<br>RUN apt-get update &amp;&amp; apt-get install -y python3-pip<br>COPY requirements.txt .<br>RUN pip install -r requirements.txt<br>RUN pip3 install jupyter<br>RUN useradd -ms /bin/bash demo<br>USER demo<br>WORKDIR /home/demo<br>ENTRYPOINT [&quot;jupyter&quot;, &quot;notebook&quot;,&quot;--ip=0.0.0.0&quot;</pre><p>4. Create a “requirements.txt” file inside “app” folder and add the following lines the file.</p><pre>pandas==1.4.4<br>numpy==1.23.3</pre><p>5. Open the terminal and go the “app” folder.</p><p>6. Run the following command in the terminal to build an image. Here image name is “docker_jypter_notebook”.</p><pre>docker build -t docker_jypter_notebook .</pre><p>7. Run the following command in the terminal to run the image. You will see url “<a href="http://127.0.0.1:8888/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01">http://127.0.0.1:8888/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01</a>” to run the jupyter notebook. Here port 8888 is a default.</p><pre>docker run -it docker_jypter_notebook</pre><p>Output :</p><pre>manjunathnaragund@Manjunaths-MacBook-Air-2 app % docker run -it docker_jypter_notebook<br>[I 18:59:21.703 NotebookApp] Writing notebook server cookie secret to /home/demo/.local/share/jupyter/runtime/notebook_cookie_secret<br>[I 18:59:21.830 NotebookApp] Serving notebooks from local directory: /home/demo<br>[I 18:59:21.830 NotebookApp] Jupyter Notebook 6.4.12 is running at:<br>[I 18:59:21.830 NotebookApp] [&lt;http://b4f3a8831971:8888/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01&gt;](&lt;http://b4f3a8831971:8888/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01&gt;)<br>[I 18:59:21.830 NotebookApp]  or [&lt;http://127.0.0.1:8888/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01&gt;](&lt;http://127.0.0.1:8888/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01&gt;)<br>[I 18:59:21.830 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).<br>[W 18:59:21.831 NotebookApp] No web browser found: could not locate runnable browser.<br>[C 18:59:21.831 NotebookApp]<br><br>To access the notebook, open this file in a browser:<br>    file:///home/demo/.local/share/jupyter/runtime/nbserver-1-open.html<br>Or copy and paste one of these URLs:<br>    &lt;http://b4f3a8831971:8888/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01&gt;<br> or &lt;http://127.0.0.1:8888/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01&gt; </pre><p>8. Now Finally, we are ready to launch our container and run jupyter notebook and we will see the same result as above command.</p><pre>docker run -p 1234:8888 docker_jypter_notebook</pre><p>9. Before opening the url “<a href="http://127.0.0.1:8888/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01">http://127.0.0.1:8888/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01</a>” replace the default port number “8888” with “1234”. And copy the new port url and paste it in browser.</p><p>ex: <a href="http://127.0.0.1:1234/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01">http://127.0.0.1:1234/?token=7dae896a7e2ce6ff5c064183f0c4fe15be01fb12fea75d01</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0CpICSI_yux_pH6vB9R-w.png" /></figure><p>Now you can use like a local jupyter notebook.</p><h3>Conclusion</h3><p>I hope now you have some understanding of how to open/run the jupyter notebook inside docker.</p><ul><li>It is a software platform that allows you to build, test, and deploy applications quickly.</li><li>It provides the ability to package and run an application in a loosely isolated environment called a container</li><li>In order to create a docker image, we use a “Dockerfile”.</li><li>The docker file is just a way to create your docker image.</li><li>“docker build -t image_name:version .” Is used to build your own custom image using docker.</li><li>“docker run -p 1234:8888 image_name:version” is used to start the container.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=665c5c4abda4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>