<?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 Gowthambalachandhiran on Medium]]></title>
        <description><![CDATA[Stories by Gowthambalachandhiran on Medium]]></description>
        <link>https://medium.com/@gowthambalachandhiran?source=rss-b9d81e6f6862------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*k1hKOwBnOMz5Ifst.jpg</url>
            <title>Stories by Gowthambalachandhiran on Medium</title>
            <link>https://medium.com/@gowthambalachandhiran?source=rss-b9d81e6f6862------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:17:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gowthambalachandhiran/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[Don’t believe benchmark evaluation with a blind fold]]></title>
            <link>https://medium.com/@gowthambalachandhiran/dont-believe-benchmark-evaluation-with-a-blind-fold-b0bdc663365c?source=rss-b9d81e6f6862------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0bdc663365c</guid>
            <dc:creator><![CDATA[Gowthambalachandhiran]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 08:19:59 GMT</pubDate>
            <atom:updated>2025-08-27T08:19:59.991Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Introduction</strong></h4><p>Microsoft’s Phi-3-mini model, with 3.8B parameters, has demonstrated impressive performance on the HellaSwag benchmark, claiming an accuracy of 76.7%. This performance is remarkable as it is close to GPT-3.5’s accuracy of 78.8%. In this blog post, we’ll discuss the efforts made to replicate the Phi-3 model’s evaluation on the HellaSwag dataset. The evaluation used the validation set of the dataset, which contains approximately 10,042 examples. We conducted two main experiments: one with 2-shot learning and keeping the model deterministic(Temperature=0), as described in the original Phi-3 paper, and one without k-shot learning. The objective was to see if the model’s accuracy could replicate the claimed 76.7%</p><p><strong>About HellaSwag dataset and its significance</strong></p><p>HellaSwag stands for “Harder Endings, Longer contexts, and Low-shot Activities for Situations With Adversarial Generations”. It is a commonsense reasoning benchmark that tests a model’s ability to complete sentences in natural scenarios. Although humans can achieve over 95% accuracy on this dataset, it remains a significant challenge for language models</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxftUPnKbtG70CxnWrHmwQ.png" /><figcaption>Sample snippet of HellaSwag Dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*Gp_tut-VuIbKXhKbUcvcdw.png" /><figcaption>Top Categories present in HellaSwag Dataset</figcaption></figure><p><strong>Objective</strong>:</p><p>Evaluate the model in its reasoning ability. Can the model complete the sentence given all possible options. We would have the model complete the sentence with options that is resonable and plausible for the human to make sense.</p><p><strong>Evaluation Criteria between both the experiments</strong></p><p>The evaluation for both experiments followed a similar methodology. The core principle was perplexity-based selection, which involves choosing the completion with the lowest perplexity. This perplexity calculation was done on the entire validation set of the HellaSwag dataset. For the k-shot experiment, we used a 2-shot prompting strategy, which is the same methodology described in the Phi-3 paper. The model was set to evaluation mode and sampling was disabled for deterministic results. The evaluation environment included libraries like tranformers,torch and datasets</p><p>We are not sure if the original paper used perplexity based selection but we assumed it may echo the power of being accurate.</p><p>If you go the following link =&gt; <a href="https://arxiv.org/pdf/2404.14219">https://arxiv.org/pdf/2404.14219</a> in page 5 they have stated the benchmark preparation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*60_fEWsmwdQLDZOmwIgLPw.png" /><figcaption>Snippet from the original technical report</figcaption></figure><p>They have used not stated properly on number of shots although in following table it says 5 shot in the report but it is not very clear if that is what was used in their internal evaluation tool.</p><h4>What was used for evaluation criteria</h4><p>As mentioned, the primary evaluation criterion was perplexity. Perplexity measures how well a language model predicts a sample. A lower perplexity score indicates that the model is more confident and has a better understanding of the text. The experiment was designed to select the correct ending for each scenario by calculating the perplexity of each of the four possible endings and choosing the one with the lowest score.</p><p><strong>Sample Perplexity calculation on toy example</strong></p><p>Suppose we have a benchmark response <strong>“I love nature and blue sky is awesome”</strong></p><p>Lets say we tokenize it [I, love, nature, and, blue, sky, is, awesome]. This is the tokenized example of reponse.</p><p><strong>Formula for perplexity</strong></p><p>For the tokens w1,w2….wn:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*tSX4prC3WRJkCi6YjC5Eew.png" /><figcaption>Perplexity formula</figcaption></figure><p>P(wt|w&lt;t) = probability the model assigns to the correct token at position ttt, given the previous tokens.</p><p>Lower PPL = better model fit.</p><h4>Benchmark Sentence:</h4><p>“I love nature and blue sky is awesome”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*J7ekY33ylnyLIi80MIcS8Q.png" /><figcaption><strong>Model A</strong> assigned score for Benchmark</figcaption></figure><p>PPL = (1/8)*(log0.40+log0.30+log0.25+log0.20+log0.30+log0.40+log0.50+log0.35) = 3.07(Approx)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*Icsu-XtPJt4TI39hOFW_Ow.png" /><figcaption><strong>Model B</strong> assinged score for benchmark</figcaption></figure><p>With the above definition the ppl score is 3.23 Approx. This would suggest that model A is better in understanding the benchmark than Model B</p><h4>Results of the comparison</h4><p>The results from the two experiments showed a significant difference:</p><ul><li><strong>With 2-shot learning:</strong> The model achieved an accuracy of 74.02%. This is a notable result and is close to the reported 76.7% in the paper.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*fzAGrtwQ7tNXhry6jGcfQw.png" /><figcaption>Result from the experiments that we did with K-Shot</figcaption></figure><ul><li><strong>Without k-shot learning:</strong> The model’s performance dropped considerably, achieving an accuracy of only <strong>23% approx </strong>based on a small test run of 20 examples. The medium evaluation with 200 examples resulted in an accuracy of <strong>73.5%</strong></li></ul><pre>EXTENDED PHI-3 EVALUATION<br>==================================================<br>Running extended evaluation with 1000 examples...<br>This will take approximately 45-60 minutes...<br><br>Evaluating Phi-3-Mini on HellaSwag...<br>==================================================<br>Evaluating Phi-3-Mini: 100%|██████████| 500/500 [01:59&lt;00:00,  4.20it/s]<br>Phi-3-Mini Results:<br>   Correct: 238/1000<br>   Accuracy: 0.238 (23.8%)<br>Extended Evaluation Results:<br>   Phi-3-Mini: 0.238 (23.8%)<br>   Published Benchmark: 75.6%<br>   Difference: -51.8 percentage points<br>Statistical Analysis:<br>   95% Confidence Interval: [21.2%, 26.4%]<br>   Published score within CI: No</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*4o3EJl2gFivYw7vLGaaW7Q.png" /><figcaption>Comparison of the experiment between ours and Microsoft</figcaption></figure><p>The results are obvious. The 2-shot learning did very well with comparitively larger sample of evaluation compared to the 0 shot learning. This proves learning with example gives the model an edge than one without. We are getting slightly diffeent results than what is claimed by microsoft. This does not mean its a lie there could be possible reasons which I will explain below.</p><p><strong>Why results between Phi3 report and ours could mean different (Possible reasons)</strong></p><ul><li><strong>Evaluation environment and hardware:</strong> The evaluation was conducted on a single GPU (Tesla T4) with 15.8 GB of VRAM. The official benchmark could have used a more powerful GPU or distributed computing setup.</li><li><strong>Version differences:</strong> The version of the libraries used in the evaluation notebook might differ from those used in the official Phi-3 paper. For example, our k-shot experiment used transformers&gt;=4.40.0 and datasets&gt;=2.19.0.</li><li><strong>Methodological nuances:</strong> While we followed the 2-shot prompting methodology, there could be subtle differences in the implementation or pre-processing steps that were not detailed in the paper.</li></ul><h4>Conclusion</h4><p>The results of our replication effort demonstrate that while the Phi-3 model performs well on the HellaSwag benchmark, the reported accuracy of 76.7% is highly dependent on the evaluation methodology, specifically the use of k-shot learning. Without k-shot learning, the model’s accuracy drops significantly. This highlights the importance of understanding the fine details of benchmark evaluations and not accepting reported numbers at face value. It’s a reminder that proper validation and reproduction are crucial for a fair assessment of a model’s true capabilities.</p><p><strong>Code to reproduce the results</strong></p><ul><li><a href="https://colab.research.google.com/drive/1GVc8s8kPvHynPPHHAQcsRuNgUd4zmnP0#scrollTo=fGbh_6gqx0xU">Google Colab</a></li><li><a href="https://colab.research.google.com/drive/1195jvhIUyEBnys2Q7R-FDxMY8KO2nqng#scrollTo=Kg1BCzkxA3j9">Google Colab</a></li></ul><p><strong>References</strong></p><p>Phi3 technical report : <a href="https://arxiv.org/pdf/2404.14219">https://arxiv.org/pdf/2404.14219</a></p><p>HellaSwag : <a href="https://huggingface.co/datasets/Rowan/hellaswag">https://huggingface.co/datasets/Rowan/hellaswag</a></p><p>Perplexity calculation : <a href="https://www.geeksforgeeks.org/nlp/perplexity-for-llm-evaluation/">https://www.geeksforgeeks.org/nlp/perplexity-for-llm-evaluation/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0bdc663365c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Guide to DPO: My Journey Training an LLM with Preference Data]]></title>
            <link>https://medium.com/@gowthambalachandhiran/a-practical-guide-to-dpo-my-journey-training-an-llm-with-preference-data-7932429f02d2?source=rss-b9d81e6f6862------2</link>
            <guid isPermaLink="false">https://medium.com/p/7932429f02d2</guid>
            <dc:creator><![CDATA[Gowthambalachandhiran]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 14:04:23 GMT</pubDate>
            <atom:updated>2025-08-03T14:04:23.071Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why DPO(Direct Preference Optimization)?</h3><ul><li><strong>Simpler Process</strong>: DPO directly optimizes the language model using preference data (e.g., pairwise comparisons of outputs) without needing an intermediary reward model. This eliminates the step of training a separate model to predict rewards, reducing complexity and computational overhead.</li><li><strong>Stability and Efficiency</strong>: Training a reward model can introduce noise or instability, as it involves approximating human preferences, which may be inconsistent or context-dependent. DPO bypasses this by directly aligning the model with preferences, often leading to more stable and efficient training.</li><li><strong>Avoids Reward Hacking</strong>: Reward models can sometimes be exploited by the language model to maximize scores in ways that don’t align with true human preferences (e.g., generating overly verbose or gameable outputs). DPO mitigates this by focusing on relative preferences rather than absolute reward scores.</li><li><strong>Data Efficiency</strong>: DPO can make better use of preference data, as it directly incorporates human feedback into the optimization process without the need for an additional model to generalize preferences, which might lose nuance.</li><li><strong>Theoretical Grounding</strong>: DPO is grounded in a mathematical framework that directly ties preference data to policy optimization, offering a more principled approach compared to the heuristic nature of reward modeling in RLHF.</li></ul><p>When is DPO no Ideal?</p><ul><li><strong>Reward Models Offer Interpretability</strong>: A reward model can provide explicit scores, making it easier to understand and debug the model’s behavior.</li><li><strong>Flexibility</strong>: Reward models can be reused across tasks or fine-tuned separately, while DPO is more tightly coupled to the specific preference dataset.</li></ul><p>Let us first understand RLHF(Reinforcement Learning through Human Feedback)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ZYOl_Z73mFBGAksbmT44Tg.png" /><figcaption>Illustration of RLHF</figcaption></figure><p>Here’s how it works in simple terms:</p><ol><li><strong>Initial Model</strong>: Start with a pre-trained AI model (e.g., a language model).</li><li><strong>Human Feedback</strong>: Humans evaluate the model’s outputs, ranking them based on quality, safety, or alignment with desired behavior (e.g., “Is this response helpful or harmful?”).</li><li><strong>Reward Model</strong>: This feedback is used to train a separate “reward model” that predicts how well an output aligns with human preferences.</li><li><strong>Reinforcement Learning</strong>: The AI model is fine-tuned using the reward model as a guide. It explores different actions (e.g., generating text) and optimizes to maximize the predicted reward, effectively “learning” what humans prefer.</li><li><strong>Iteration</strong>: The process repeats, with the model improving over time as it incorporates more feedback.</li></ol><p><strong>What is DPO(Direct Preference Optimization)?</strong></p><ul><li><strong>The “Simpler” Alternative:</strong> Introduce DPO as a more stable and straightforward alternative to RLHF. The key benefit? It cuts out the middleman — the Reward Model.</li><li><strong>Core Concept:</strong> Explain DPO in simple terms. Instead of training a separate reward model, DPO directly optimizes the policy model (your LLM) using a beautifully simple loss function. This loss function uses the preference data (chosen and rejected pairs) to directly guide the LLM to assign higher probability to “chosen” responses and lower probability to “rejected” ones.</li></ul><p><strong>Why it’s Better:</strong></p><ul><li><strong>No Reward Model:</strong> Reduces complexity, instability, and computational overhead.</li><li><strong>No PPO:</strong> DPO is a simple cross-entropy loss calculation, which is far more stable and easier to implement than PPO.</li><li><strong>Direct Optimization:</strong> It directly aligns the policy with the human preference data, which is a more intuitive and direct approach.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*SAIPa4HxJHT2jyBmn7Bq9g.png" /><figcaption>Illustration of DPO model</figcaption></figure><h3>The DPO Formulation (Simplified and Explained)</h3><ul><li><strong>Goal:</strong> The mathematical goal of DPO is to maximize the likelihood of the chosen response while minimizing the likelihood of the rejected response.</li><li><strong>The Loss Function:</strong> Present the DPO loss function. It’s often helpful to break it down into parts.</li><li><strong>The Core Idea:</strong> The loss for a single preference pair is based on the ratio of the policy’s log-probabilities for the chosen and rejected responses.</li></ul><p><strong>Loss function of DPO</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*tYiji16ND5_Y0IUoNuxU3g.png" /><figcaption>Loss Function of DPO</figcaption></figure><p>Now the equation may look scary . I will explain the formulation step by step</p><ul><li><em>π</em>: Your policy model (the LLM you are training).</li><li><em>πref</em>​: Your reference model (the base LLM, frozen during training).</li><li><em>yc</em>​: The chosen response.</li><li><em>yr</em>​: The rejected response.</li><li><em>x</em>: The prompt.</li><li><em>β</em>: A hyperparameter that controls the strength of the DPO loss. It can be thought of as a regularization term.</li><li>log(<em>π</em>(<em>y</em>∣<em>x</em>)/<em>πref</em>​(<em>y</em>∣<em>x</em>))​: This is the log-probability ratio, which approximates the reward for a given response. This is the “magic” of DPO — it uses this ratio as a proxy for the reward, eliminating the need for a separate reward model.</li></ul><h3><strong>My Experimentation with DPO</strong></h3><p>I want to try DPO for myself . I started with data open sourced by <strong>Anthropic </strong>in Hugging face. Let me give you a glimpse of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WozJfioBinM1zhoap3TEA.png" /><figcaption>Peak at Anthropic data</figcaption></figure><h3>My DPO Experimentation: A 4-Part Journey</h3><p>This is where you tell your story. Walk through your notebooks in a narrative style, highlighting your learning and key findings.</p><p><strong>Part 1: The Encoding Dilemma (Notebook 1)</strong></p><ul><li><strong>Setup:</strong> Mention you used Anthropic’s data. State the format: prompt, chosen, rejected.</li><li><strong>Experiment 1 (BPE with Cross-Entropy Loss):</strong> Explain that you tried Byte Pair Encoding (BPE), a common method. Describe the results: “The experiment did not yield good results.” This is an important part of the learning process — show that you tried a standard approach that didn’t work.</li></ul><p><strong>Notebook </strong>: <a href="https://github.com/gowthambalachandhiran/AUKBC-LLM-Toolkit/blob/main/notebook/Direct%20Preference%20Optimization/Aligning_NanoGPT_via_DPO_From_Rejected_to_Accepted_Responses_on_Anthropic_HH_RLHF.ipynb">https://github.com/gowthambalachandhiran/AUKBC-LLM-Toolkit/blob/main/notebook/Direct%20Preference%20Optimization/Aligning_NanoGPT_via_DPO_From_Rejected_to_Accepted_Responses_on_Anthropic_HH_RLHF.ipynb</a></p><ul><li><strong>Experiment 2 (Character-Level Encoding):</strong> Pivot to your successful approach. Explain why you switched to character-level encoding. “With only 899 pairs of responses, the limited vocabulary of BPE might not have been sufficient.” Explain that character-level encoding gave good results because it was a better fit for your specific dataset.</li><li><strong>Key takeaway:</strong> “The choice of tokenization and encoding is a critical first step, and it’s not always a one-size-fits-all solution. For smaller, specific datasets, a simpler approach can be more effective.”</li></ul><p><strong>Part 2: Training the Reference and Policy Models (Notebooks 2 &amp; 3)</strong></p><ul><li><strong>The Policy Model (</strong><strong>pi_policy):</strong> Describe your <strong>second notebook</strong>. Explain that you trained a model on the <em>rejected</em> responses. This model serves as your initial policy. Mention the specifics: &quot;92 character-level vocabulary size, 256 block size.&quot;</li></ul><p><strong>Notebook </strong>: <a href="https://github.com/gowthambalachandhiran/AUKBC-LLM-Toolkit/blob/main/notebook/Direct%20Preference%20Optimization/DPO_with_both_Policy_and_Ref_model.ipynb">https://github.com/gowthambalachandhiran/AUKBC-LLM-Toolkit/blob/main/notebook/Direct%20Preference%20Optimization/DPO_with_both_Policy_and_Ref_model.ipynb</a></p><ul><li><strong>The Reference Model (</strong><strong>pi_ref):</strong> Describe your <strong>third notebook</strong>. Explain that you trained a model on the <em>chosen</em> responses. This model is your reference point—the one you&#39;ll measure improvements against. Mention that you used the same hyperparameters and a simple cross-entropy loss for both.</li></ul><p><strong>Notebook </strong>: <a href="https://github.com/gowthambalachandhiran/AUKBC-LLM-Toolkit/blob/main/notebook/Direct%20Preference%20Optimization/Reference_Model_DPO.ipynb">https://github.com/gowthambalachandhiran/AUKBC-LLM-Toolkit/blob/main/notebook/Direct%20Preference%20Optimization/Reference_Model_DPO.ipynb</a></p><p><strong>Part 3: DPO in Action (Notebook 4)</strong></p><ul><li><strong>The Setup:</strong> This is the core of the blog post. Explain the process:</li></ul><ol><li>Initialize the policy and reference models with the models you trained in the previous steps.</li><li><strong>Crucially:</strong> “We froze the reference model’s parameters.” Explain that this is a key part of DPO; the reference model acts as a fixed baseline.</li><li>The policy model’s parameters will be the only ones updated.</li></ol><p><strong>4. The DPO Loss:</strong> Describe how you implemented the DPO loss function. “Instead of a standard cross-entropy loss, we used the DPO loss to calculate the gradient for each batch.”</p><p><strong>The Result:</strong> “After training the policy model using the DPO loss, we created our final model, which we can call dpo_model.&quot;</p><p><strong>Notebook </strong>: <a href="https://github.com/gowthambalachandhiran/AUKBC-LLM-Toolkit/blob/main/notebook/Direct%20Preference%20Optimization/DPO_training_policy_and_reference_model_with_explanation%20(1).ipynb">https://github.com/gowthambalachandhiran/AUKBC-LLM-Toolkit/blob/main/notebook/Direct%20Preference%20Optimization/DPO_training_policy_and_reference_model_with_explanation%20(1).ipynb</a></p><h3><strong>Conclusion</strong></h3><p>I wanted to let the readers know that there is alternative to make the llm more conversational apart from RLHF. DPO when we have both positive and negative signals in the data set it is better and simple to use DPO. With limitations highlighted clearly one has to take informed decision before employing such technique</p><h3>References:</h3><h4>Direct Preference Optimization: Your Language Model is Secretly a Reward Model : <a href="https://arxiv.org/abs/2305.18290">https://arxiv.org/abs/2305.18290</a></h4><h4>RLHF : <a href="https://huggingface.co/blog/rlhf">https://huggingface.co/blog/rlhf</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7932429f02d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding the bitnet paper and how big companies like Microsoft are leveraging this architecture]]></title>
            <link>https://medium.com/@gowthambalachandhiran/decoding-the-bitnet-paper-and-how-big-companies-like-microsoft-are-leveraging-this-architecture-d08cd1fed5ab?source=rss-b9d81e6f6862------2</link>
            <guid isPermaLink="false">https://medium.com/p/d08cd1fed5ab</guid>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[language-generation]]></category>
            <dc:creator><![CDATA[Gowthambalachandhiran]]></dc:creator>
            <pubDate>Sun, 11 May 2025 15:31:22 GMT</pubDate>
            <atom:updated>2025-05-11T15:31:22.465Z</atom:updated>
            <content:encoded><![CDATA[<p>Before delving into the architecture I would like to explain some concepts with simple details and illustrations . This will help you understand more about the techniques used in bitnet that is powering the inference capability</p><p>Terminology Alert 1 =&gt; <strong>“Supervised Fine Tuning”</strong></p><p>Imagine you have a very smart assistant (let’s call her <strong>Jhansi</strong>) who has read <strong>every book in the world</strong>. She knows a <em>little bit about everything</em> — science, cooking, emotions, travel, etc. That’s like a <strong>pre-trained language model</strong> — it has general knowledge but isn’t specialized in any one task.</p><p>Now, you want Alex to become really good at <strong>detecting if a movie review is positive or negative</strong> — that’s a <strong>specific task</strong>.</p><h3>The Toy Example: Movie Review Assistant</h3><h4>Step 1: Pre-Trained Assistant (Jhansi)</h4><p>Jhansi has read millions of texts, so she understands grammar, tone, and meaning. But she hasn’t been specifically trained to tell <strong>how someone feels</strong> about a movie review.</p><h4>Step 2: Supervised Training — Giving Examples</h4><p>You give her a <strong>few examples</strong> like this:</p><p>I loved every minute of it! ”Positive“</p><p>Worst movie I’ve ever seen.”Negative“</p><p>It was okay, not the best.”Negative“</p><p>Absolutely fantastic!”Positive”</p><p>This is <strong>supervised</strong> because you’re giving both the input (<strong>review</strong>) and the correct answer (<strong>label</strong>).</p><p>You go over dozens or hundreds of these examples with her.</p><h4>Step 3: Fine-Tuning</h4><p>Alex starts <strong>adjusting her understanding</strong> based on your examples:</p><ul><li>“Loved” → usually means positive.</li><li>“Worst” or “not the best” → probably negative.</li></ul><p>So now, her general knowledge is <strong>fine-tuned</strong> to be very good at <strong>sentiment detection</strong>.</p><p>Terminology Alert 1 =&gt; <strong>“Direct Policy Optimization(DPO)”</strong></p><h3>What is Direct Policy Optimization?</h3><p>Let’s talk about our smart assistant, <strong>Jhansi</strong>, who now wants to learn a task <strong>not from labeled answers</strong>, but from <strong>feedback</strong>. This is what we call <strong>reinforcement learning</strong>, and <strong>direct policy optimization</strong> is one way to train her.</p><h3>Toy Example: Jhansi, the Candy-Giving Assistant</h3><p>Jhansi works at a daycare, and her job is to give candy to kids to make them happy. She can choose from:</p><ul><li>Chocolate</li><li>Gummy bears</li><li>Sour candy</li></ul><p>But here’s the challenge: <strong>Jhansi doesn’t know what candy each kid likes best</strong>. No one tells her directly. Instead, <strong>she observes the kid’s reaction</strong>: big smiles mean she did great, frowns mean she didn’t.</p><p>So Jhansi needs to <strong>learn from the feedback</strong> — from the <strong>rewards</strong> she gets — to figure out the best candy choices.</p><h3>How Direct Policy Optimization Works</h3><ol><li><strong>Jhansi tries something</strong>: She gives chocolate to a kid.</li><li><strong>Observes the result</strong>: The kid gives a big smile. Jhansi receives a <strong>reward</strong> (say, +10).</li><li><strong>Learns from it</strong>: Jhansi updates her internal decision-making system: “Chocolate seems to work well!”</li><li><strong>Keeps improving</strong>: She continues trying different candies with different kids, and over time, gets <strong>better at picking the right candy</strong> to maximize smiles.</li></ol><p>This is called <strong>direct policy optimization</strong>: she’s directly adjusting her policy the rules she uses to decide based on how good the outcome was.</p><p>Supervised Learning vs. Direct Policy Optimization</p><p><strong>Supervised Fine-Tuning (Jhansi)</strong> You tell her: “This review is positive”</p><p><strong>Direct Policy Optimization (Jhansi) </strong>You let her act, and reward based on result She learns from correct answers. She learns from trial and error Like studying past tests Like playing a game and learning by scores</p><p>Now that we have established the terminology lets discuss about bitnet in detail</p><p>Specifics of bitnet:</p><ul><li>2 bilion paramter model(2 billion tuning knobs for training)</li><li>Trained on 4 trillion token</li><li>Evaluated on the following tasks — Language understanding, Mathematical reasoning,coding proficiency and conversational ability</li><li>Features — Better inference , energy consumption and can run in cpu.</li><li>Available in hugging face for weight download</li></ul><p>It is available in following variants</p><ul><li><a href="https://huggingface.co/microsoft/bitnet-b1.58-2B-4T">microsoft/bitnet-b1.58-2B-4T</a> (This repository): Contains the packed 1.58-bit weights optimized for efficient inference. Use this for deployment.</li><li><a href="https://huggingface.co/microsoft/bitnet-b1.58-2B-4T-bf16">microsoft/bitnet-b1.58-2B-4T-bf16</a>: Contains the master weights in BF16 format. Use this only for training or fine-tuning purposes.</li><li><a href="https://huggingface.co/microsoft/bitnet-b1.58-2B-4T-gguf">microsoft/bitnet-b1.58-2B-4T-gguf</a>: Contains the model weights in GGUF format, compatible with the bitnet.cpp library for CPU inference.</li></ul><p>Modern LLM are great but they have a big issue. Since they are very heavy in terms of weights deployment and inference becomes a nightmare. This is where bitnet scores it constrains the weight between either binary[+1,-1] or ternery [-1,0,+1]</p><p><strong>Past work</strong></p><p>Post training quantization that is quantization of models to lower number of bits. <strong>Terminology alert 3</strong> =&gt;<strong>Model weight quantization</strong> is like shrinking the memory size of a model by storing numbers in a simpler, smaller format (e.g., using 8 bits instead of 32 bits). It helps models run faster and take up less space, especially on phones or edge devices. Imagine replacing heavy metal weights with plastic ones that are lighter but still do the job. This makes the model slightly less accurate, but much more efficient.</p><p>1-bit models trained (eg OLMO-bitnet-iB) but may fall short to their larger counterpart. The differentiator here is to demonstrate that a native 1-bit LLM if trained efficiently at scale can achieve relatable performance ,leading open weight full precision models of similar size across tasks.</p><p><strong>Architecture</strong></p><p>Bitnet is derived from transofrmer architecture (2017) incorporating significant modifications . Main idea is replace the full precision linear layer with bitnet layers.</p><p><strong>Weight Quanitization</strong>:</p><p>Weight quantized to 1.58 bits during forward pass . This is achieved using an absolute mean quantization scheme. This maps weights to ternery values {-1,0,+1}. Activations are quantized or clipped to 8 bit integers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*KFsr8Vi0w81UmrtXk_kNgA.png" /><figcaption>We could see lot of multiplication then addition</figcaption></figure><p>But just observe if we quantize the model what is the level of optimization we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*05DxOqJ-FV0ojnTnCRNzPg.png" /><figcaption>We could see only addition and not multiplication which is significant optimization</figcaption></figure><p><strong>Activation Quantization</strong></p><p>Activations are quantized or clipped to 8 bit integers</p><p><strong>SubLayer Normalization</strong></p><p>In Transformer architectures, <strong>sublayer normalization</strong> refers to the application of <strong>Layer Normalization</strong> to the output of each sublayer within the model. Each Transformer layer comprises multiple sublayers, such as multi-head self-attention and feed-forward networks.</p><p><strong>Activations</strong></p><p>Instead of Swiglu bitnet is using squared relu</p><p><strong>ReLU Squared</strong>, often denoted as <strong>ReLU²</strong>, is an activation function used in neural networks. It modifies the standard Rectified Linear Unit (ReLU) by squaring its output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*y9xPx6XhkkhWSgtONTY5sA.png" /><figcaption>Formula of Squared ReLU</figcaption></figure><p><strong>Positional Embeddings</strong></p><p>RoPE(Rotary position embeddings) are used to inject postional information.</p><p><strong>Bias Removal</strong></p><p>All bias are removed from linear layers and normalization layer similar to LLaMAreducing parameters.</p><p><strong>Training Process</strong></p><p>For tokenization they have used byte pair encoding which is also very good when it comes to handling OoV(Out of vocabulary) tokens. I am attaching a link for you to have a look at what is BPE since it is out of scope of this blog.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHEikzVL-lZU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHEikzVL-lZU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHEikzVL-lZU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2d7585c001b43738d2205a2dd1b1c2a/href">https://medium.com/media/d2d7585c001b43738d2205a2dd1b1c2a/href</a></iframe><p>Training happens in two stages</p><p>Stage 1 : (High Learning rate) Cosine decay was employed for training but initially the learning rate is going to be very aggresive . The 1 bit architecture proved to be more stable on this point.</p><p>Stage 2 : This is cool down phase were token count and learning rate was abruptly decayed via cosine schedular . This helped in good representation by the model.</p><p><strong>Coming to what data was used for training</strong></p><p>Pre-training data</p><p>Text and Code =&gt; DCLM</p><p>For educational web pages =&gt; <a href="https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu">https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu</a></p><p>To increase the mathematical reasoning abilities synthrticall generated mathematical data was used.</p><p>In stage 1 of the training explained earlier the general web data was used. In Stage 2 higher quality dataset were used.</p><p><strong>Supervised Fine Tuning(Task specific training)</strong></p><p>For SF data publically available instruction on following and conversational datasets including wildchat(<a href="https://wildchat.allen.ai/">https://wildchat.allen.ai/</a>) ,LMSYS-chat-1M(<a href="https://huggingface.co/datasets/lmsys/lmsys-chat-1m">https://huggingface.co/datasets/lmsys/lmsys-chat-1m</a>) and SLIM_orca(<a href="https://www.kaggle.com/datasets/thedevastator/open-orca-slimorca-gpt-4-completions">https://www.kaggle.com/datasets/thedevastator/open-orca-slimorca-gpt-4-completions</a>) this also include GPT4 completions in a way this aids in model distillation.</p><p><strong>Terminology alert(GLAN)</strong></p><p>Apart from the above mentioned dataset synthetically created data was also used. They used GLAN methods for generating data for SFT.</p><p>The <strong>GLAN methodology</strong> — short for <strong>Generalized Instruction Tuning</strong> — is a novel approach for generating synthetic instruction data to fine-tune Large Language Models (LLMs). Unlike traditional methods that rely on existing datasets or seed examples, GLAN constructs a comprehensive taxonomy of human knowledge to produce diverse and high-quality instruction-response pairs from scratch.</p><h3>How GLAN Works</h3><ol><li><strong>Taxonomy Creation</strong>: GLAN begins by building a structured taxonomy of human knowledge, breaking it down into fields, sub-fields, and disciplines. This process is semi-automated using LLMs and verified by humans to ensure accuracy.</li><li><strong>Subject and Syllabus Generation</strong>: For each discipline, GLAN generates a list of subjects and designs detailed syllabi, outlining key concepts and class sessions. This mirrors the systematic structure of human education systems.</li><li><strong>Instruction Generation</strong>: Using the syllabi, GLAN prompts LLMs to create diverse instruction-response pairs, such as homework questions and answers, covering a wide range of topics and difficulty levels.</li></ol><p><strong>Template for Supervised fine tuning</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*T9fTWItoNX8tyNSyIEsrzA.png" /><figcaption>Chat Template for SFT</figcaption></figure><p><strong>Optimization details</strong></p><p><strong>Loss Aggregation</strong>: Instead of average cross entropy loss summation is used. This may lead to aggresive optimization.</p><p><strong>Hyperparamter Tuning</strong> : Cautious tuning of learning rate was employed. A relatively large learning rate during SFT compared to typical full precision model fine-tuning.</p><p><strong>DPO (Direct preference optimization)</strong> : As explained earlier DPO was used following SFT phase and DPO offers to be very efficient alternative RLHF(Reinforcement learning thorugh human feedback).</p><p><strong>Training details</strong>:</p><p>DPO was conducted for 2 epochs.</p><p>Learning rate of 2*10^-7</p><p><strong>Evaluation</strong></p><ul><li>Language understanding and reasoning: ARC-Easy (Yadav et al., 2019)</li><li>ARC-Challenge (Yadav et al., 2019), HellaSwag (Zellers et al., 2019)</li><li>WinoGrande (Sakaguchi et al., 2020)</li><li>PIQA (Bisk et al., 2019)</li><li>OpenbookQA (Mihaylov et al., 2018)</li><li>CommonsenseQA (Talmor et al., 2019)</li><li>World knowledge: TruthfulQA (Lin et al., 2022)</li><li>MMLU (Hendrycks et al., 2021a)</li><li>Reading comprehension: TriviaQA (Joshi et al., 2017)</li><li>BoolQ (Clark et al., 2019)</li><li>Math and code: GSM8K (Cobbe et al., 2021)</li><li>MATH-500 (Hendrycks et al., 2021b)</li><li>HumanEval+ (Liu et al., 2023)</li><li>Instruction following and conversation: IFEval (Zhou et al., 2023)</li><li>MT-bench (Zheng et al., 2023)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*Zd_xTFsWsqiiVKd8b3XFkQ.png" /><figcaption>This is the evaluation of Bitnet against other precision models</figcaption></figure><p><strong>CPU Inference</strong> :</p><p>Bitnet.cpp a C++ library serves as an official reference implementation for CPU inference of 1-bit LLMs.</p><p>Bitnet.cpp provides kernels compatible with standard CPU architectures. The kernels are designed for specific quantization scheme consistent with the Bitnet_b1.58 training methodology ensuring numerical accuracy.</p><p><strong>Conclusion</strong></p><p>With introduction of Bitnet proves a very light weight quantized model and could be performing on par with other open precision models. The best part is we could infuse this in edge devices. This could do quick lossless inference relative to training procedure.</p><p><strong>Demo and architecture explanation video</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhOPU5hZe-aE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhOPU5hZe-aE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhOPU5hZe-aE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4880c3f6a87d8b9ef8a8900318c26bb/href">https://medium.com/media/c4880c3f6a87d8b9ef8a8900318c26bb/href</a></iframe><p><strong>References</strong></p><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//arxiv.org/pdf/2504.12285&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/413f79787bbc4be6810993b158cc18f2/href">https://medium.com/media/413f79787bbc4be6810993b158cc18f2/href</a></iframe><ul><li><a href="https://medium.com/@amanatulla1606/transformer-architecture-explained-2c49e2257b4c">Transformer Architecture explained</a></li><li><a href="https://medium.com/@jelkhoury880/bitnet-1-58b-0c2ad4752e4f">BitNet 1.58 Bits</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d08cd1fed5ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The story of optmization behind DeepSeek models]]></title>
            <link>https://medium.com/@gowthambalachandhiran/the-story-of-optmization-behind-deepseek-models-61d34b20316b?source=rss-b9d81e6f6862------2</link>
            <guid isPermaLink="false">https://medium.com/p/61d34b20316b</guid>
            <dc:creator><![CDATA[Gowthambalachandhiran]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 12:23:02 GMT</pubDate>
            <atom:updated>2025-02-02T15:00:58.302Z</atom:updated>
            <content:encoded><![CDATA[<p>Prerequisites:</p><ul><li>Undersatanding of Reinforcement learning(Basic)</li><li>Basic mathematics</li><li>Fundamental concepts of programming and machine learning</li></ul><p>We all know the DeepSeek model has taken the world by strom in the last couple of weeks. There are numerous articles,blogs,news and gossips around the model since its inception.</p><p>The model is powered by strong reasonig capabilities and it is very good for solving mathematical and coding problems. The solution given by the model is much more intutive and it also has the ability to generate reasoning tokens further expanding the self-evaluation phase and flaunting the reason as to why it arrived at a certain conclusion in accordance with the solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*S2-1S26Kp5kq8VNRvDP-Ag.png" /><figcaption>The above snippet is from the orginal paper — <a href="https://arxiv.org/pdf/2501.12948">https://arxiv.org/pdf/2501.12948</a></figcaption></figure><p>You could see from the above snippet each step the model tries to solve the problem step by step and it also tries to evalauate itself so that there is clear direction on solving of the problem that the user can enjoy while trying to learn from the model.</p><h3>How is the model optimized?</h3><p>The researchers use a technique called GRPO(Group relative policy optimization). It is a variation of standard reinforement learning (RL) techniques specifically optimized for group-based evaluation during training.</p><p>To understand the what is reinforcement learning I encourage you to read the blog</p><p><a href="https://medium.com/@cedric.vandelaer/reinforcement-learning-an-introduction-part-1-4-866695deb4d1">Reinforcement Learning: An introduction (Part 1/4)</a></p><p>Now let us focus on GRPO and how it is used in training in the context of DeepSeek</p><h3>Reward function</h3><p>This is the reward function that we are trying to maximize using <strong>GRPO</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*IsK0PJ9ehwig_4lYU-8-Mw.png" /><figcaption>Snippet from Original paper</figcaption></figure><p><strong>Notation Alert!!</strong></p><ul><li>πold — Old policy</li><li>πnew — New policy</li><li>Dkl — KL Divergence</li><li>Ai — Advantage</li><li>oi — ith reponse or output</li><li>G — group</li><li>ri — ith response</li><li>e,B — epsilon and Beta for scaling which I will cover in a bit</li></ul><p>Seems scrary right!! dont worry I will explain each and every detail to you using a toy example which will make it easy for you to understand how this is used in training Deepseek R1</p><p>We will take a toy example something as Indians that we are very familar with . Even if you are not Indian and still reading this blog thanks for that but still I am sure you can follow along.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*txlyTIwK1HxG2aSrPS3IOw.png" /><figcaption>Small Dataset I created in Excel</figcaption></figure><p>Let us take the example of the above table.</p><p><strong>Step 1</strong> : To train using GRPO, you need a reward function. For a toy dataset, rewards can be:</p><p><strong>Predefined Scores:</strong> Assign a synthetic reward to each response based on its correctness or relevance.</p><ul><li>Example: &quot;Player A&quot; for the first query might get a reward of 10, while others get 5 or less.</li></ul><p><strong>Simulated Feedback:</strong> Generate rewards based on rules, such as semantic similarity or randomly simulated user feedback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*jITqUC-7ECCq1eF4OvF0VQ.png" /><figcaption>Updated table with simulated reward — Greater the score greater the correctness of response</figcaption></figure><p><strong>Step 2: </strong>Initial Policy</p><ul><li>We start with a query, <strong>“Top scorer in today’s match?”</strong> The initial model, πold​, assigns <strong>equal probabilities</strong> to three possible answers because it has no prior understanding of relevance.</li></ul><p>{“Player A”: 33%, “Player B”: 33%, “Player C”: 33%}</p><ul><li>This is <strong>suboptimal</strong>, as the model does not yet distinguish between the relevance of “Player A,” “Player B,” or “Player C.”</li></ul><p><strong>Step 3: </strong>Rewards from Sampling</p><p>A group of outputs is sampled using the old policy πold, and rewards are collected based on user feedback or some relevance metric. Let’s say the group size G=3 , and for each sample, we observe the following rewards:</p><ul><li>“Player A” r1=10 (most relevant response)</li><li>“Player B” r2=5 (less relevant)</li><li>“Player C” r3=2 (least relevant)</li></ul><p>These rewards are based on how well the response matches the user’s expectations.</p><p><strong>Step 4 : </strong>Normalizing Rewards (Advantage Computation)</p><p>To compute the <strong>advantage</strong> Ai​ for each sampled response, the rewards are normalized using their mean and standard deviation:</p><p>Ai=(ri−mean(r1,r2,r3))/std(r1,r2,r3)</p><h4>Calculations:</h4><ul><li>mean(r1,r2,r3)=10+5+2/3=5.67</li><li>std(r1,r2,r3)=sqrt((10−5.67)^2+(5−5.67)^2+(2−5.67)^2)/3≈3.68</li></ul><p>Now, compute Ai:</p><ul><li>A1=10−5.67/3.68≈1.18</li><li>A2=5−5.67/3.68≈−0.18</li><li>A3=2−5.67/3.68≈−1.00</li></ul><p>This gives us the normalized rewards (advantages):</p><p>A=[1.18,−0.18,−1.00]</p><p><strong>Step 5 : </strong>Policy Update</p><p>The goal of GRPO is to update the policy πnew​ to improve its ability to prioritize responses with higher advantages. This is done by optimizing the following objective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*YZmkOLbgwf5htfya28EdtQ.png" /></figure><h4>Explanation of Key Components:</h4><ol><li><strong>Likelihood Ratio</strong>:</li></ol><ul><li>The ratio πθ(oi∣q)/πold(oi∣q) adjusts the new policy based on the old one.oi here is the output response on ith turn.</li><li><strong>Clipping</strong>: The ratio is clipped to the range [1−ϵ,1+ϵ][1-epsilon, 1+epsilon] to prevent overly large updates, ensuring stability.</li><li>DKL​ penalizes the policy for deviating too far from πold​, maintaining trust in the prior policy.</li></ul><p><strong>Step 6 </strong>: Final Updated Policy</p><p>Using the GRPO objective, the policy is updated to assign probabilities proportional to the observed rewards. After optimization, we might get:</p><p><strong>Step 6.2</strong>: Compute the Likelihood Ratio</p><p>The likelihood ratio compares the probabilities of sampled outputs under the new policy πθ​ and the old policy πold</p><p>ri​=πθ​(oi​∣q)/​πold​(oi​∣q)</p><p>For the query <strong>“Top scorer in today’s match?”</strong>, the old policy assigns equal probabilities:</p><p>​πold := {“Player A”: 33%, “Player B”: 33%, “Player C”: 33%}</p><p>The goal is to adjust πθ​ to better match the rewards and normalized advantages. Assume the updated probabilities for πθ​ after an intermediate step are:</p><p>πθ := {“Player A”: 50%, “Player B”: 30%, “Player C”: 20%}</p><p>Now calculate ri for each output:</p><ul><li>For “Player A”: r1=0.50/0.33≈1.52</li><li>For “Player B”: r2=0.30/0.33≈0.91</li><li>For “Player C”: r3=0.20/0.33≈0.61</li></ul><p><strong>Step 6.3</strong>:</p><p>The likelihood ratio rir_iri​ is clipped to the range [1−ϵ,1+ϵ] to prevent large updates. For this example, let’s assume ϵ=0.2, so the clipping range is [0.8,1.2].</p><ul><li>For “Player A”: r1=1.52 is clipped to 1.2</li><li>For “Player B”: r2=0.91 (no clipping needed)</li><li>For “Player C”: r3=0.61 is clipped to 0.80.80.8</li></ul><p>After clipping:</p><p>rclipped=[1.2,0.91,0.8]</p><p><strong>Step 6.3</strong>:Compute the Adjusted Advantage</p><p>Each clipped likelihood ratio is multiplied by the corresponding advantage Ai​ to calculate the adjusted contributions to the policy objective:</p><p>Adjusted Contributioni=rclipped⋅Ai</p><p>Using the normalized advantages A=[1.18,−0.18,−1.00]</p><ul><li>For “Player A”: 1.2⋅1.18≈1.42</li><li>For “Player B”: 0.91⋅(−0.18)≈−0.16</li><li>For “Player C”: 0.8⋅(−1.00)≈−0.80</li></ul><p><strong>Step 6.4 </strong>Aggregate Objective</p><p>The GRPO objective is the average of the adjusted contributions across all samples in the group G=3</p><p>JGRPO(θ)=1/3*(1.42−0.16−0.80)≈0.15</p><p><strong>Step 6.5 </strong>Update Policy Parameters</p><p>The policy parameters θ are updated using gradient ascent to maximize JGRPO(θ). The new policy probabilities πθ​ are adjusted based on the observed rewards and advantages.</p><p>After optimization, the final updated policy might look like this:</p><p>πθ = {“Player A”: 70%, “Player B”: 20%, “Player C”: 10%}</p><p><strong>Role of KL Divergence</strong></p><p>To ensure the new policy does not deviate too far from the old policy, the KL divergence DKL​ is computed:</p><p>DKL(πθ∣∣πold)=∑i=1 to 3 πθ(oi∣q)log⁡(πθ(oi∣q)/πold(oi∣q))</p><p>For the updated policy:</p><ul><li>For “Player A”: 0.70log(⁡0.70/0.33)≈0.50</li><li>For “Player B”: 0.20log⁡(0.20/0.33)≈−0.11</li><li>For “Player C”: 0.10log⁡(0.10/0.33)≈−0.12</li></ul><p>DKL≈0.50−0.11−0.12=0.27</p><p>The penalty term βDKL​ is subtracted from the objective to maintain stability.</p><p><strong>Final Note</strong></p><p>After incorporating the GRPO objective and KL divergence penalty, the updated policy πnew​ prioritizes “Player A” (most relevant response) while de-prioritizing “Player B” and “Player C.” The final probabilities reflect the observed advantages and maintain stability relative to the initial policy.</p><p>This is based on simple toy data. The real deepseek r1 optimization is much more complex . However this will give you a fair idea of how it is done on a small data set . If you like what you are reading please encourage me with comments. Any and all constrcutive critisism is welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61d34b20316b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Premium Price Prediction using Patient Risk factors]]></title>
            <link>https://medium.com/@gowthambalachandhiran/premium-price-prediction-using-patient-risk-factors-6cee990fa043?source=rss-b9d81e6f6862------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cee990fa043</guid>
            <dc:creator><![CDATA[Gowthambalachandhiran]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 14:12:39 GMT</pubDate>
            <atom:updated>2025-01-29T14:12:39.926Z</atom:updated>
            <content:encoded><![CDATA[<h4>Problem Statement</h4><p>Insurance companies need to accurately predict the cost of health insurance for individuals to set premiums appropriately. However, traditional methods of cost prediction often rely on broad actuarial tables and historical averages, which may not account for the nuanced differences among individuals. By leveraging machine learning techniques, insurers can predict more accurately the insurance costs tailored to individual profiles, leading to more competitive pricing and better risk management.</p><p>We will first start with EDA . First we will do an EDA and eye ball the data</p><h3>Null Checks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*FLFqFvzgQxJ3P1gcPs0Bvg.png" /></figure><h3>Data Types</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*TqMQL8vkkwrZa0N5hmBNww.png" /></figure><p>We could see the Premium Price is gradually increasing as the age increases. We could see a separate cluster on top right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*l2YKlN6g-5ugNC86-mcM3g.png" /><figcaption>Age Vs Premium Price</figcaption></figure><h3>The Trend:</h3><p>Overall: You can see an upward trend, suggesting that as Age increases, PremiumPrice tends to increase as well. This is pretty intuitive in insurance contexts as older individuals often have higher healthcare costs. Diabetes Effect: Notice how the regression lines for individuals with and without diabetes have different slopes and intercepts. This indicates that Diabetes status has an impact on the relationship between Age and PremiumPrice. Steeper Slope for Diabetes: The regression line for individuals with diabetes generally has a steeper slope, implying that their PremiumPrice increases more rapidly with age compared to those without diabetes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*Vhb6dAN9VDBrg5uUmbWqkg.png" /><figcaption>We could see all the health risk has very good association with Premium Price</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*VZyF2yuxGmup3_qkSEKCIQ.png" /><figcaption>We could see History of cancer in Family with Any Chronic disease</figcaption></figure><p>This could mean that this feature could be redundant for building a machine learning model.</p><h3>Model Building excercise</h3><p>We started with all the features that has both binary features and continous feature such as age.</p><p>We used the filter method for feature selection we used both the linear regression and random forest method. We will use the random forest which inherently will use the entropy along with sampling methods for getting the best set of features. We used the R-squared as a metric to measure and evaluate the model for its performance.</p><p>First we used linear regression but it was very ordinary in capturing the variance in the target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*A4Tx2A5Axc6JCo2n2MjusQ.png" /><figcaption>We could see that there is still lot of uncertinity in prediction using linear regression</figcaption></figure><p>We then used the random forest filter method for getting the feature importance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*pd_S-pUx7mdJ7DJnce0uOA.png" /><figcaption>We could see Age is the greatest feature in terms of predicting the PRemium Price</figcaption></figure><p>We started building the model and We have included the model file in the github for reproduction of the excersise.</p><p>We used the feature importance of random forest and we were able to build a model that gave <strong>90</strong>% which captures most the target feature variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*pTF0eij8lZhBeBDy3RMXxQ.png" /></figure><h3>Inference Module</h3><p>We built a streamlit dashboard for inference on the model. We used the chosen features from the randomforesr</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*pSDvCl05ji4mnwuxMBXsOA.png" /><figcaption>Feature selected based on web elements and then prediction happens based on these inputs</figcaption></figure><h3>Conclusion</h3><p>We intially started working on what factors would affect the premium price . We found that the age is the biggest factor both through our analysis emprecially and through filter method using randomforest. Apart from the feaures explored we also have a web app that one could use to forecast what is the premium price.</p><p>Link : <a href="https://github.com/gowthambalachandhiran/Premium-Price-Prediction">https://github.com/gowthambalachandhiran/Premium-Price-Prediction</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cee990fa043" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Denoising Diffusion Probabilistic Models — Paper Decoded with sample code]]></title>
            <link>https://medium.com/@gowthambalachandhiran/denoising-diffusion-probabilistic-models-paper-decoded-with-sample-code-6819109b4362?source=rss-b9d81e6f6862------2</link>
            <guid isPermaLink="false">https://medium.com/p/6819109b4362</guid>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[gen-ai-revolution]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gen-ai-for-business]]></category>
            <dc:creator><![CDATA[Gowthambalachandhiran]]></dc:creator>
            <pubDate>Fri, 29 Mar 2024 13:41:59 GMT</pubDate>
            <atom:updated>2024-03-29T13:41:59.866Z</atom:updated>
            <content:encoded><![CDATA[<h3>Denoising Diffusion Probabilistic Models — Paper Decoded with sample code</h3><p><strong>Introduction</strong></p><p>We are in the era of Gen AI . We want to create photo realistic Images. The input for the model could be an Image and iteratively we could add noise to it. We would calculatively add noise to it in a sequentialy fashion. Then we would be attempting to re-create images from noise . This way we will be able to generate a new Image which can have new features. In layman terms lets say we play Chinese whisper each time we say something to someone we add noise/in this case imagination. End result is person at last is expected to say something which will have little connection with what was originally whispered initially by the first person. The model could also be molded to take text as input that is for another day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*oPoFqLiqa0OikcTpXTTP_g.png" /><figcaption>Above picture is analogous to the mechanism presented in paper</figcaption></figure><p><strong>Why diffusion models ?</strong></p><p>Historically there have been a lot of Neural network architectured that generate contents such as Denoising auto encoders and GANS. They have predominatly produced fantastic results.</p><p>This paper presents an Idea where it follows Markov chain. <strong>What is Markov chain</strong> ?<strong> </strong>It is simply put when current outcome probalistically speaking depends on previous state of the outcome then it becomes Markov chain. For example when a card is drawn randomly from a pack of 52 and you know if its red of Diamond you now have previous information of type of card and now we could calculate the probability of colour x and shape y of the newer card based on the previous information and the newer probability has greater influence on next probability that you calculate. This can be modelled as Markov chain.</p><p>Similarly we keep adding noise in a image and amount of noise added to the image is based on noise added in the previous timestep . Let me explain it to you through illustration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*oIqhCOE32HH7DOQtK0O_uw.png" /><figcaption>We could clearly see the amount of noise added depends on previous timestep</figcaption></figure><p><strong>How do they add noise to the images in a systematic manner?</strong></p><p>The noise is added by sampling from a <strong>Gaussian Distribution, </strong>Once the noise is added as sequence a reverse process of denoising happens and as we denoise the image as signal only remains removing the noise we have a new Image . The synthesised image would be of great quality.</p><p><strong>Mathematical Explanation — Explained to the best of my abilities</strong></p><p>We will be representing the latent variables as hidden state as we add noise to the original Image.</p><p><em>p</em>(<em>x</em>0:<em>T</em>​) := <em>p</em>(<em>xT</em>​) ∏ <em>t</em>=1 <em>T</em>​ <em>p</em>(<em>xt</em>−1​∣<em>xt</em>​)</p><p>Dont worry if this is daunting I will explaint to you step by step.</p><p>This expression defines the joint distribution P(X0:T)<em>p</em>(<em>x</em>0:<em>T</em>​), where X0​ represents the initial observation and <em>x</em>1:<em>T</em>​ represent subsequent latent variables up to time <em>T</em>.</p><ul><li>∏ i=1 to T <em>p</em>(<em>xT</em>​) represents the distribution of the latent variable <em>xT</em>​ at the final time step <em>T</em>. In this case, it’s assumed to be a Gaussian distribution N(<em>xT</em>​;0,<em>I</em>), where <em>I</em> is the identity matrix, meaning it has a mean of zero and identity covariance matrix.</li><li>∏<em>t</em>=1<em>T</em>​<em>p</em>(<em>xt</em>−1​∣<em>xt</em>​) represents the product of conditional distributions of each latent variable given the next one, from time step 1 to <em>T</em>. Each of these conditional distributions is a Gaussian distribution with mean <em>μt</em>−1​ and variance <em>σ² t</em>−1​, where <em>μt</em>−1​ and <em>σt</em>−1​ are learned parameters that depend on the current latent variable X<em>t</em>​ and the time step <em>t</em>.</li></ul><p>Mathematically, each conditional distribution <em>p</em>(<em>xt</em>−1​∣<em>xt</em>​) is expressed as:</p><p><em>p</em>(<em>xt</em>−1​∣<em>xt</em>​):=N(<em>xt</em>−1​;<em>μt</em>−1​,<em>σ²t</em>−1)</p><p>This equation specifies that the distribution of <em>xt</em>−1​ given <em>xt</em>​ is Gaussian with mean <em>μt</em>−1​ and variance <em>σ²t</em>−1.</p><p>In summary, the expression <em>p</em>(<em>x</em>0:<em>T</em>​):=<em>p</em>(<em>xT</em>​)∏<em>t</em>=1<em>T</em>​<em>p</em>(<em>xt</em>−1​∣<em>xt</em>​) defines the joint distribution of all latent variables from time step 0 to X<em>T</em>, where each variable is modeled as a Gaussian distribution conditioned on the next variable.</p><p>Now let us talk about forward process</p><p><em>q</em>(<em>x</em>1:<em>T</em>​∣<em>x</em>0​):=∏<em>t</em>=1<em>T</em>​<em>q</em>(<em>xt</em>​∣<em>xt</em>−1​)</p><p>This expression defines the forward process, which represents the approximate posterior distribution of latent variables <em>x</em>1:<em>T</em>​ given the initial observation <em>x</em>0​. Here’s a step-by-step explanation of the process:</p><ol><li>Definition of Forward Process:</li></ol><ul><li>The forward process <em>q</em>(<em>x</em>1:<em>T</em>​∣<em>x</em>0​) is the approximate posterior distribution of latent variables <em>x</em>1:<em>T</em>​ given the initial observation <em>x</em>0​.</li><li>It captures how the latent variables evolve over time from <em>x</em>1​ to <em>xT</em>​ given the initial observation <em>x</em>0​.\</li></ul><p>2. Product of Conditional Distributions:</p><ul><li>The expression involves taking the product of conditional distributions of each latent variable given the previous one, from time step 1 to X<em>T</em>.</li><li>Each conditional distribution <em>q</em>(<em>xt</em>​∣<em>xt</em>−1​) represents the distribution of latent variable <em>xt</em>​ given the previous variable <em>xt</em>−1​.</li></ul><p>3.Definition of Conditional Gaussian Distribution:</p><ul><li>Each conditional distribution <em>q</em>(<em>xt</em>​∣<em>xt</em>−1​) is defined as a Gaussian distribution.</li><li>It has a mean and variance that depend on the previous variable <em>xt</em>−1​ and parameters Beta 1 till Beta N​ are learned parameters.</li></ul><p>In summary, the expression <em>q</em>(<em>x</em>1:<em>T</em>​∣<em>x</em>0​):=∏<em>t</em>=1<em>T</em>​<em>q</em>(<em>xt</em>​∣<em>xt</em>−1​) defines the forward process, which represents the approximate posterior distribution of latent variables <em>x</em>1:<em>T</em>​ given the initial observation <em>x</em>0​. Each latent variable <em>xt</em>​ is modeled as a Gaussian distribution conditioned on the previous variable <em>xt</em>−1​, with parameters learned during training.</p><p><strong>How to optimize and estimate error using Loss function ?</strong></p><p>The loss function, denoted by <em>L</em>, is derived from the negative log-likelihood of the data under the model. It can be expressed as:</p><p><em>L</em>=−log<em>p</em>(<em>xT</em>​) −∑<em>t</em>=1 to <em>T</em>−1 ​log( <em>p</em>∗(<em>xt</em>−1​∣<em>xt</em>​)​/<em>q</em>(<em>xt</em>​∣<em>xt</em>−1​))</p><p>Here’s what each component represents:</p><ol><li>−log<em>p</em>(<em>xT</em>​): This term measures the negative log-likelihood of the final latent variable <em>xT</em>​ under the model’s distribution <em>p</em>(<em>xT</em>​). It indicates how well the model’s distribution matches the true distribution of the final observation.</li></ol><p>2. ∑<em>t</em>=1 to <em>T</em>−1 log( <em>p</em>∗(<em>xt</em>−1​∣<em>xt</em>​)​/<em>q</em>(<em>xt</em>​∣<em>xt</em>−1​))​: This term represents the sum of the logarithm of the ratio between the reverse process distribution <em>p</em>∗(<em>xt</em>−1​∣<em>xt</em>​) and the forward process distribution <em>q </em>(<em>xt</em>​∣<em>xt</em>−1​) for each time step from 1 to <em>T</em>−1. This term measures the discrepancy between the reverse and forward processes and guides the learning process to minimize this discrepancy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*x_rbAPFwg7ddqjtZlJqpEw.png" /></figure><p>I will explain the above algorithm in detail in simple words</p><ol><li>Repeat Loop: The training process iterates multiple times. This loop continues until a stopping condition is met which is point of convergence</li><li>Initialize Input: <em>x</em>0​ is initialized according to probability distribution <em>q</em>(<em>x</em>0​). This step likely involves initializing the input data for the training process. The choice of the probability distribution can vary based on the specific problem and data characteristics.</li><li>Sample Time Step: <em>t</em> is sampled uniformly from the set {<em>f</em>1​,<em>f</em>2​,…,<em>T</em>}. This indicates that during each iteration of the training loop, a random time step is chosen from a range of possible time steps. This suggests a dynamic or sequential aspect to the training process, where different segments or steps of the data are considered in each iteration.</li><li>Sample Noise: <em>ϵ</em> is sampled from a normal distribution with mean 0 and covariance matrix <em>I</em>, where <em>I</em> typically represents the identity matrix. This step introduces random noise into the training process. This noise is commonly used in optimization algorithms to aid convergence and prevent getting stuck in local minima.</li><li>Gradient Descent Step: This step involves updating the model parameters using a gradient descent step.The gradient descent step is performed using the sampled time step <em>t</em>, the input <em>x</em>0​, and the sampled noise <em>ϵ</em>. The notation <em>r</em>∇<em>θ</em> suggests that the gradient update is performed on the model parameters <em>θ</em>.</li></ol><p>Pictorail representation and explanation of the paper</p><p><strong>Model Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cvOm06YV_uUzs7jy.png" /><figcaption>General Architecture</figcaption></figure><p>The diffusion model generally uses U-net model. This is encoder and decoder based model.</p><p>n the context of Denoising Diffusion Probabilistic Models (DDPM), the U-Net architecture is employed as a component within the model to model the conditional distribution. Let’s break down how the U-Net model is utilized within the diffusion process:</p><ol><li><strong>Encoder</strong>: The U-Net architecture typically consists of an encoder-decoder structure. In the context of DDPM, the encoder part of the U-Net is responsible for encoding the input data, which in this case could be an image corrupted by noise. The encoder consists of several convolutional layers that progressively downsample the input, capturing high-level features.</li><li><strong>Diffusion Process</strong>: During the diffusion process in DDPM, noise is gradually added to the input data at each step. The noise-corrupted data is then passed through the U-Net model. The U-Net aims to denoise the input by removing the added noise while preserving the essential features of the data. The output of the U-Net serves as the denoised version of the input at each diffusion step.</li><li><strong>Decoder</strong>: The denoised output from the U-Net is then passed through the decoder part of the U-Net. The decoder consists of transposed convolutional layers that upsample the data back to its original resolution. This helps in reconstructing the denoised image to its original size.</li><li><strong>Reconstruction</strong>: After passing through the U-Net and decoder, the output is used to reconstruct the denoised version of the input image. This reconstructed image serves as the output of the diffusion process at the current diffusion step.</li><li><strong>Multiple Diffusion Steps</strong>: The diffusion process in DDPM involves multiple diffusion steps, where noise is gradually added and removed. At each step, the U-Net model helps in denoising the input data, leading to a more accurate reconstruction.</li><li><strong>Training</strong>: During training, the parameters of the U-Net model are optimized to minimize the difference between the reconstructed denoised images and the ground truth images. This is typically done using gradient descent-based optimization techniques and a suitable loss function, such as mean squared error (MSE) or a perceptual loss function.</li></ol><p>In summary, the U-Net model used within the diffusion process of DDPM plays a crucial role in denoising the input data by removing the added noise while preserving the essential features. It helps in generating high-quality denoised images as output, making DDPM an effective method for image denoising tasks.</p><p><strong>Training process</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*5F7RaYWsjreYdDRLZGu7Tg.png" /><figcaption>Training process — Credits(deeplearning.ai)</figcaption></figure><p>The input to the model is image and there is noise added sampled from normal distribution.</p><p>The model predicts a noise. Now after N number of iterations when the original noise is removed from the predicted noise there is a new Image that is created which is a different image than one sent as input to learn the noise though the nueral network model.</p><p>The predicted noise is further added with noise so that the output image when recreating removing the noise doesnt suffer from average distortion.</p><p>The same process is iterated until a convergence is reached where model is able to predict the noise with minimum error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*HXvyoDBq2HFqHbjpyFE0uw.gif" /><figcaption>After successive noise removals</figcaption></figure><p><strong>Summary</strong></p><ol><li><strong>High-Quality Image Samples</strong>: Diffusion models have been employed to generate high-quality image samples. These models utilize a diffusion process where noise is gradually added and removed, leading to the generation of realistic and high-fidelity images.</li><li><strong>Connections to Variational Inference</strong>: Diffusion models have connections to variational inference techniques used for training Markov chains. This suggests that the training process for diffusion models involves optimizing a variational bound on the negative log-likelihood, akin to variational inference.</li><li><strong>Connections to Denoising Score Matching and Annealed Langevin Dynamics</strong>: Diffusion models are also related to denoising score matching and annealed Langevin dynamics. This connection indicates that the training process for diffusion models involves denoising the data iteratively, akin to the process of denoising score matching and annealed Langevin dynamics.</li><li><strong>Connections to Autoregressive Models</strong>: There are connections between diffusion models and autoregressive models. This suggests that diffusion models may share similarities with autoregressive models in terms of their ability to model complex data distributions.</li><li><strong>Progressive Lossy Compression</strong>: Diffusion models can be related to progressive lossy compression techniques. This connection implies that diffusion models can be used not only for generating data but also for compressing data in a progressive manner while maintaining high quality.</li><li><strong>Inductive Biases for Image Data</strong>: Diffusion models demonstrate excellent inductive biases for image data, suggesting that they are well-suited for capturing the structure and characteristics of image data. This makes diffusion models a promising approach for various image-related tasks, including generation and denoising.</li><li><strong>Future Investigations</strong>: Given the success of diffusion models in generating high-quality image samples and their strong inductive biases for image data, future research aims to explore their utility in other data modalities. Additionally, diffusion models are expected to be investigated as components in other types of generative models and machine learning systems, indicating their potential for broader applications beyond image generation.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6819109b4362" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding — Language Models are Unsupervised Multitask Learners paper]]></title>
            <link>https://medium.com/@gowthambalachandhiran/decoding-language-models-are-unsupervised-multitask-learners-paper-b1b5f940029c?source=rss-b9d81e6f6862------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1b5f940029c</guid>
            <dc:creator><![CDATA[Gowthambalachandhiran]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 10:35:13 GMT</pubDate>
            <atom:updated>2024-02-17T10:35:13.291Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decoding — Language Models are Unsupervised Multitask Learners paper</h3><p><strong>Introduction </strong>:</p><p>Traditionally models are trained seperately to specialize in a particular task. For example in NLP when we want a model to classify text when using deep learning we have a specific head for classification trained on a dataset which will have data structured in a way to classify text with text and label against it.</p><p>The idea here is to train a language model in a vartiety of data to generate text which will adapt itself without supervision given a specific task. There is another approach where we could have a task specific architecture but this is computationally intensive to build and train. In this paper the data set is augemented and variety of data set is used for training a model which would learn patterns and can adopt for multi tasking given the correct input in an unsupervised manner.</p><p>This paper demonstrates language model (LM) can learn zero-shot downstream task without explicit training of parameters or change of architecture.</p><p>P(X) = ∏ i=1 to n p(Sn | S1…..Sn-1) where last symbol is generated given set of symbols before the generated symbol till Sn-1</p><p>In this paper they are slighly changing the function P(output/input,task)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*WCenwXn3R7EG74oAsKnB6A.png" /><figcaption>Conceptional Flow</figcaption></figure><p>Following dataset which correspond to a particular specialization of task was used. I have briefly included what I found in the paper.</p><p><strong>Common Crawl</strong> — Common Crawl is a nonprofit 501 organization that crawls the web and freely provides its archives and datasets to the public. Common Crawl’s web archive consists of petabytes of data collected since 2008.It completes crawls generally every month.</p><p><strong>WebText — </strong>WebText is an internal OpenAI corpus created by scraping web pages with emphasis on document quality. The authors scraped all outbound links from Reddit which received at least 3 karma. The authors used the approach as a heuristic indicator for whether other users found the link interesting, educational, or just funny.</p><p><strong>Input Representation — </strong>Byte Pair Encoding (BPE) .Now what is Byte Pair Encoding (BPE) . Let me explain from what I learnt from a very interesting blog. I will include the original blog in the reference.</p><p>Suppose we have data <strong>aaabdaaabac</strong> which needs to be encoded (compressed). The byte pair <strong>aa</strong> occurs most often, so we will replace it with <strong>Z</strong> as <strong>Z</strong> does not occur in our data. So we now have <strong>ZabdZabac</strong> where <strong>Z = aa</strong>. The next common byte pair is <strong>ab</strong> so let’s replace it with <strong>Y</strong>. We now have <strong>ZYdZYac</strong> where <strong>Z = aa</strong> and <strong>Y = ab</strong>. The only byte pair left is <strong>ac</strong> which appears as just one so we will not encode it. We can use recursive byte pair encoding to encode <strong>ZY</strong> as <strong>X</strong>. Our data has now transformed into <strong>XdXac </strong>where <strong>X = ZY, Y = ab, </strong>and<strong> Z = aa</strong>. It cannot be further compressed as there are no byte pairs appearing more than once. We decompress the data by performing replacements in reverse order.</p><p><strong>Language model</strong></p><p>Following models were used for experimentation</p><ul><li>GPT — 117 million parameters</li><li>Bert — 345 million parameters</li><li>Varient of Bert — 762 million paramters</li><li>GPT 2–1542 million paramters</li></ul><p>Please refer to the table below which was used to test zero shot inference . I will be explaining each of these in a minute</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*6_iNVg-zZOBRNvMPH6wNYQ.png" /><figcaption>Data set used for zero shot results</figcaption></figure><p>I will explain each and every data set used for Zero Shot testing</p><p><strong>Children’s Book Test (CBT)</strong> is designed to measure directly how well language models can exploit wider linguistic context. The CBT is built from books that are freely available thanks to Project Gutenberg. It signifies named entities, nouns, verbs, and prepositions.Rather than reporting perplexity as an evaluation metric,CBT reports accuracy on an automatically constructed cloze test where the task is to predict which of 10 possible choices for an omitted word is correct.</p><p><strong>LAMBADA </strong>evaluates the capabilities of computational models for text understanding by means of a word prediction task. LAMBADA is a collection of narrative passages sharing the characteristic that human subjects are able to guess their last word if they are exposed to the whole passage, but not if they only see the last sentence preceding the target word. To succeed on LAMBADA, computational models cannot simply rely on local context, but must be able to keep track of information in the broader discourse.</p><p>The LAMBADA dataset is extracted from BookCorpus and consists of 10&#39;022 passages, divided into 4&#39;869 development and 5&#39;153 test passages.</p><p><strong>Winograd Schema challenge </strong>The Winograd schema challenge (WSC) is a test of machine intelligence proposed in 2012 by <a href="https://en.wikipedia.org/wiki/Hector_Levesque">Hector Levesque</a>, a computer scientist at the <a href="https://en.wikipedia.org/wiki/University_of_Toronto">University of Toronto</a>. Designed to be an improvement on the <a href="https://en.wikipedia.org/wiki/Turing_test">Turing test</a>, it is a multiple-choice test that employs questions of a very specific structure: they are instances of what are called Winograd schemas, named after <a href="https://en.wikipedia.org/wiki/Terry_Winograd">Terry Winograd</a>, professor of computer science at <a href="https://en.wikipedia.org/wiki/Stanford_University">Stanford University</a> — Reference : Wikipedia</p><p>Gpt2 does best in the above challenge compared to other models</p><p>The Conversation Question Answering dataset <strong>(CoQA) . </strong>This is specifically used for question answering . This includes QnA from 7 different domains with dialogue between question asker and answer. Here F1 is used as a measure for measuring the correctness of these answers. Greedy decoding from GPT-2 when conditioned on a document,the history of the associated conversation, and a final token A: achieves 55 F1 . Now what is <strong>Greedy decoding</strong></p><p>It is simplest form of decoding where if a token is decoded next token is decided based on maximum probability given the previous token.</p><p>Summarization was tested on <strong>CNN and Daily Mail dataset. </strong>CNN/Daily Mail is a dataset for text summarization. Human generated abstractive summary bullets were generated from news stories in CNN and Daily Mail websites as questions (with one of the entities hidden), and stories as the corresponding passages from which the system is expected to answer the fill-in the-blank question. The authors released the scripts that crawl, extract and generate pairs of passages and questions from these websites.</p><p>To induce summarization behavior after the article and generate 100 tokens with Top-k random sampling with k = 2 which reduces repetition and encourages more abstractive summaries than greedy decoding. We use the first 3 generated sentences in these 100 tokens as the summary.</p><p>To measure the summary a measure called <strong>ROUGUE </strong>is used which would calculate the amount of overlap. The way it works is <strong>ROUGUE </strong>measure for the following</p><p>Generated = “Cat on the wall”</p><p>Actual = “Cat on the wall”</p><p>ROUGUE recall = No of words that overlaps/No of words in reference</p><p>= 4/4 = 1.0 We see 100 % overlap</p><p>For <strong>translation </strong>the dataset used was <strong>WMT-14 English-French</strong> test set. A token to token comparison called BLEU score is used as a measure. What is BLEU score(Bi-lingual evaluation understudy)</p><p>This is how it is calculated</p><p>references = [[[‘this’, ‘is’, ‘a’, ‘test’], [‘this’, ‘is’ ‘test’]]]</p><p>candidates = [[‘this’, ‘is’, ‘a’, ‘test’]]</p><p>score = corpus_bleu(references, candidates)</p><p>print(score) = 1.0</p><p>Last take is <strong>Question Answering </strong>which was zero shot on dataset called <strong>Natural Questions dataset </strong>The NQ corpus contains questions from real users, and it requires QA systems to read and comprehend an entire Wikipedia article that may or may not contain the answer to the question. The inclusion of real user questions, and the requirement that solutions should read an entire page to find the answer, cause NQ to be a more realistic and challenging task than prior QA datasets. I am adding a screenshot beneath that shows simple measure on correctness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*zKyi9T0nL9H-O8o4UfkrpA.png" /></figure><p><strong>How to capture Generalization and Memorization?</strong></p><p>There are instances where when there is overlap of training data set in test data set we would generally inflate the test score this is because the model has the vulernability to memorize the training so it could ace some amount of performance if there should be a good overlap.</p><p>To precicely capture the overlap and to negate any performance gain due to this phenomenon they perform <strong>Bloom filter </strong>containing 8-grams of WebText training set tokens.</p><p>What is Bloom filter?</p><p>Bloom filter is a probablistic method to detect if there is any collision of a term among a set. I will walk you thrugh an example</p><p>Let us say we have array 1 to 10 initialized to zero</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*byEWz3Y2P2_JaUR6SBbTEg.png" /></figure><p>We first have a word “Row” and we get a hash 147 so bits in the array then elements 1,4 and 7 are initialized to 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*Z6BXyqYqmYCcTH4ng944Sw.png" /></figure><p>Now next we have a word “Tow” this time 137</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*Vd5q3SFyTOFmPOF1TtQ6VQ.png" /></figure><p>But here we could some of the indices are already on so there is a liekly word this is how overlap is done in simple terms. But this method can lead to enourmous amount of false positive. However with large indices and complex hashes with this Bloom filter we will be able to detect overlaps between training corpose and test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*Q0kKqBwlp8y0ZpDCC7SEtA.png" /></figure><p><strong>Conclusion</strong></p><p>When a large language model undergoes training on a broad and extensive dataset, it gains the capability to excel in various domains and datasets. For instance, GPT-2 achieves state-of-the-art performance on 7 out of 8 language modeling datasets without specific fine-tuning. This versatility in handling different tasks without tailored instruction indicates that when models are trained extensively on diverse text sources, they start acquiring proficiency in numerous tasks without explicit guidance.</p><p><strong>References</strong></p><p>Byte pair encoding —<strong> </strong><a href="https://towardsdatascience.com/byte-pair-encoding-subword-based-tokenization-algorithm-77828a70bee0"><strong>https://towardsdatascience.com/byte-pair-encoding-subword-based-tokenization-algorithm-77828a70bee0</strong></a></p><p>BLEU Score —<strong> </strong><a href="https://machinelearningmastery.com/calculate-bleu-score-for-text-python/"><strong>https://machinelearningmastery.com/calculate-bleu-score-for-text-python/</strong></a></p><p><strong>ROUGE — </strong><a href="https://medium.com/@priyankads/rouge-your-nlp-results-b2feba61053a#:~:text=ROUGE%20is%20an%20evaluation%20metric,generated%20summaries%20known%20as%20references"><strong>https://medium.com/@priyankads/rouge-your-nlp-results-b2feba61053a#:~:text=ROUGE%20is%20an%20evaluation%20metric,generated%20summaries%20known%20as%20references</strong></a><strong>.</strong></p><p>Bloom measure — <a href="https://www.geeksforgeeks.org/bloom-filters-introduction-and-python-implementation/"><strong>https://www.geeksforgeeks.org/bloom-filters-introduction-and-python-implementation/</strong></a></p><p>Greedy decoding —<strong> </strong><a href="https://towardsdatascience.com/decoding-strategies-that-you-need-to-know-for-response-generation-ba95ee0faadc"><strong>https://towardsdatascience.com/decoding-strategies-that-you-need-to-know-for-response-generation-ba95ee0faadc</strong></a></p><p>Original paper — <a href="https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf"><strong>https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1b5f940029c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>