<?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 Sauradeep Debnath on Medium]]></title>
        <description><![CDATA[Stories by Sauradeep Debnath on Medium]]></description>
        <link>https://medium.com/@saurad44?source=rss-82fbcbdab085------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*da0MYi8i_BlysL0u.jpg</url>
            <title>Stories by Sauradeep Debnath on Medium</title>
            <link>https://medium.com/@saurad44?source=rss-82fbcbdab085------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:31:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saurad44/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[From Classical Recommender Systems to Generative Recommendation : A Survey of the Evolution…]]></title>
            <link>https://blog.gopenai.com/from-classical-recommenders-to-llms-the-evolution-of-recommendation-systems-f51689dd064b?source=rss-82fbcbdab085------2</link>
            <guid isPermaLink="false">https://medium.com/p/f51689dd064b</guid>
            <category><![CDATA[llms-as-recommender]]></category>
            <category><![CDATA[collaborative-filtering]]></category>
            <category><![CDATA[generative-recommendat]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[netflix-recommendations]]></category>
            <dc:creator><![CDATA[Sauradeep Debnath]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 07:50:58 GMT</pubDate>
            <atom:updated>2026-10-15T11:34:11.651Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Classical Recommender Systems to Generative Recommendation : A Survey of the Evolution, Architecture and Evolving Paradigms</h3><h4>Why this shift ? Does it even work in real production systems ? How does it work ?</h4><p>Hey everyone, today’s topic is going be to a really fascinating.</p><p>Many of us might have seen on social media that Netflix recently ( 21 Aug, 2026) published a paper on how they are gradually moving to a LLM-based recommendation/ranking. That piqued my interest and I realized, it wasn’t the only one. YouTube, Spotify, Kuaishou ( China’s leading short media platform) have had<em> phenomenal success</em> lately in similar experiments.</p><p>Turned out, in stead of relying on hand engineered features, leveraging pretrained LLM as backbone helped them to take advantage of their rich capabilities &amp; world knowledge &amp; figure — while at the same time, they came up with innovative ideas to adapt the LLM to their own recommendation catalog.</p><p>This frankly surprised me because I used to think that classical recommendation algo or even a custom bi-Encoder model would perform better in Recommendation, usually considered as a discriminative task.</p><p>However, I found that as early as May 2025, the PrefillOnly paper points out how these days we have started using LLMs in discriminative tasks e.g. recommender systems, credit verification, data labelling.</p><p>But how do you align LLMs to dynamic and large catalog, give personalized recommendations while keeping both short term &amp; long term history, while keeping the latency, hallucination &amp; training &amp; inference cost low?</p><p>Let us quickly cover the evolution of latest recommendation algos — and the fascinating new ideas they introduced, starting with a quick refresh.</p><h3>PHASE 1: Classical Recommendation algos:</h3><p>As many of us are aware, traditionally, recommendation engines are implemented via these 3 methods ( &amp; their variations) :</p><ol><li><em>Collaborative Filtering</em>( 1992–1994)- current user’s preference vs other “similar” users. Rows — users, columns — items to be recommended. Matrix Factorization(2006) is one of the newer ways to implement this algo.</li><li><em>Content Based Filtering</em>(1997)- whatever the items the user liked, recommend “similar” items</li><li><em>Multi armed bandits</em> ( 1950s-60s) — optimize &amp; find the right balance between Exploration &amp; Exploitation; the newer version, Contextual bandits (2007) also add user &amp; environment data to the process for a more personalized recommendations.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNF4U_mWk-t08NJlqtwUuw.png" /><figcaption>Collaborative Filtering, Source — <a href="https://developers.google.com/machine-learning/recommendation/collaborative/basics">https://developers.google.com/machine-learning/recommendation/collaborative/basics</a></figcaption></figure><p><em>NOTE</em>: Some of the timelines ( years mentioned in the bracket) above may be approximate .</p><h3>Downsides of Classical Recommender Systems:</h3><p>Of course, these systems are cheap, predictable and are excellent at capturing user-interactions but they do have their limitations.</p><p>DeepMind( TIGER, 2023) states Generative Recommender systems are better at generalization ( no prior interaction/ “<strong>cold start</strong>”).</p><p>Spotify(GLIDE, 2026) argues that classical recommendation systems typically emphasize long term interaction rather than <strong>dynamic </strong>context “timely updates during a commute, brief entertainment between meetings, or deeper topical exploration at home”. Also, recommendations at the discovery surface vs mid session should vary.</p><p>Netflix (GenRec 2026) mentions that because their current production system has thousands of <strong>hand-crafted </strong>features, onboarding a new content is a nightmare in terms of “ feature engineering, modelarchitecture design, infrastructure changes, and experimentation.”</p><h3>PHASE 2: Neural Recommendation ( Non LLM):</h3><p>Starting from GRU4REC(2015), NARM(2017), AttRec(2018), BERT4Rec(2019), Transformer4REC(2021), S3Rec(2020) — there has been a lot of research on this front. Please note these are all <strong>bi-Encoders — </strong>two encoders for encoding the ‘query’ and ‘candidate’ ( item &amp; user OR past-history &amp; next-item) and then get tehir dot product. But these all probably got overshadowed by a Encoder-Decoder( Seq2Seq) model, TIGER.</p><h3><strong>DeepMind/ NeurIPS 2023, TIGER</strong>: <strong>Recommender systems with generative retrieval:</strong></h3><p><em>Understanding this paper becomes really important for all the subsequent models we discuss later in this blog.</em></p><p>They generate <strong>semantic tokens</strong> for each items using its content features (titles, descriptions, images etc) via auto- encoder RQ-VAE. In short, first we get semantic <em>embeddings </em>from that content ( say using BERT, Sentence-T5 etc.) — which is then <em>quantized </em>into Semantic IDs, which are hierarchical in nature. More on this under the “advantage” section below, where we talk about the “codebook”.</p><p>As the authors mention, “For example, an item with Semantic ID (10, 21, 35) should be more similar to one with Semantic ID (10, 21, 40), than an item with ID (10, 23, 32).” — due to overlapping Semantic IDs. If you read about RQ VAE exact implementation in the paper, you will understand it more concretely, but you can think of it being similar to different places of a decimal number. 1<strong><em>1</em></strong>3 -1<strong><em>1</em></strong>2&lt; 1<strong><em>2</em></strong>3–1<strong><em>1</em></strong>2.</p><p>The concept of Semantic IDs is also used in Netflix’s GenRec(2026 August) and Spotify’s GLIDE(2026 March).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*fNnc3CWUdq4wfoVnZfMuUw.png" /><figcaption>Source — TIGER, DeepMind, NeurIPS 2023</figcaption></figure><p>Given a sequence of objects ( semantic IDs), the transformer is trained to predict the next item semantic ID ( e.g. next purchase or click).</p><p><strong><em>Model </em></strong>— T5X- 13 Million parameters</p><p><strong>Advantage over Bi Encoders</strong>: Unlike most of its predecessor Encoder model,<strong> no need to store the embeddings of each new item</strong> ( which could be a scaling nightmare). Instead, for each element of Sematic ID ( e.g. it is usually a tuple of 2 or 3 numbers) — <em>only </em>a separate quantization “<em>codebook</em>” is needed to be stored in order to generate the semantic IDS. At each level of the SID, we try to map the residual to the nearest embedding ( usually out of 256 available options) in that layer’s codebook. Overall, <strong>the codebook size is exponentially small </strong>compared to the bi-encoder embeddings ( e.g. item-user, history-next_item etc.)</p><p><strong><em>Downsides</em></strong>: Unlike more recent rec ommenders with LLM backbone that we will discuss next, they don’t have the broad-world knowledge &amp; rich capabilities of an LLM, or can’t steer their recommendations with flexible prompts.</p><h3>PHASE 3 : LLM based recommendations:</h3><p>Here’s a quick intro to these category of models, courtesy of GenRec authors. All of these start with a pretrained foundational LLM. The individual papers mention how these models perform way better than TIGER / Large Embedding Models in terms of various metrics like NDCG, recall etc. But they each take different routes:</p><ol><li>Google’s PLUM model for YouTube: adapts the LLM via task specific fine tuning to Semantic ID generation.</li><li>Spotify’s GLIDE → instruction following over Semantic ID catalog</li><li>OneRec Think — Qwen3 backbone + session list generation + Preference Alignment.</li></ol><p><strong><em>So how is GenRec better ?</em></strong> Most of these use Beam search (high latency) — GenRec has single forward pass.</p><p>Here are some more info on each of these models:</p><h3>2025 Feb, OneRec: Unifying Retrieve and Rank with Generative Recommender and Iterative Preference Alignment:</h3><p>With OneRec( ~<strong>1B MoE model</strong>), the <strong>Kuaishou </strong>( China’s leading short-video platform with hundreds of millions of daily users) saw an 1.6% watch time increase( and outperforms TIGER 1B in terms of session watch time &amp; like probability).</p><p>Unlike TIGER which uses RQ-VAE for semantic ID generation, OneRec uses Balanced KMeans clustering to get the optimized codebook. Also uses DPO for preference learning instead of RLHF.</p><p>The deployed model takes user history (watch, like, follow, share) as input and recommends 5–10 ( a “session of”) videos instead of just predicting the next video— termed as ‘session list generation’ .(<em> No separate domain adaptation/continued pre training</em>)</p><p><strong>Model </strong>— T5 MoE ~1B. Encoder for encoding user history, Decoder for session list generation — trained with cross entropy loss for next-token prediction</p><h3>2025 Oct, DeepMind/YouTube, PLUM: Adapting Pre-trained Language Models for Industrial-scale Generative Recommendations:</h3><p>The Semantic ID(SID) generation process adds some enhancements to RQ VAE introduced in the TIGER paper — e.g. they can now capture multiple modalities, have a multi -resolution codebook &amp; captures co-occurance (e.g. videos watched together) in addition to the intrinsic item content.</p><p><strong><em>Model</em></strong>- 900M Activated parameter from Gemini 1.5 MoE(4.2B in total)</p><p><strong>Step1</strong> : The CPT( continued PreTraining) familiarizes the LLM to user watch history data plus video corpus ( SID + textual features) by training the model with <em>next-token prediction</em> on a data equal mixture of both user history+video metadata ( SID, title, description, ASR cpations, channel name etc).</p><p><strong>Step 2</strong>: the generative retrieval uses next SID prediction. For training the retriever, the clicked videos from user logs are taken as Ground Truth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*Nd7a1-5ExUw25gMXLRZW3g.png" /><figcaption>Source- PLUM(2025)</figcaption></figure><h3>2026 March, Deploying Semantic ID-based Generative Retrieval for Large-Scale Podcast Discovery at Spotify:</h3><p>GLIDE( Grounded LLM for InterestDiscovery rEcommendations) increased streaming by 5.4% for ‘non-habitual shows’ ( shows with &lt;10 mins listening time in last 28 days) and new show discovery by 14.3% when tested across millions of users.</p><p><strong>Step 1 : Domain Adaptation ( “Semantic Grounding”):</strong></p><p>The SIDs are quantized from multi-lingual embeddings. So they do not have do not have domain specific understanding. So then we train with bidirectional translation objective — generating metadata from SID and vice versa. It is a two step process:</p><p>a. In stage 1, we learn the correct token embeddings for each of the SID tokens (you can think of them as new word tokens or “new vocabulary items” as the paper calls it), keeping the Transformer backbone frozen.</p><p>b. Freeze both the embedding &amp; the model, and finetune with LoRA.</p><p>They reason that these steps prevent catastrophic forgetting, as opposed to full finetuning of the model.</p><p><strong>Key Novel ideas in Step 2</strong>—</p><ol><li>In addition to short term( recent listening history) is not enough. But <strong>user interests, topics &amp; historical behavior can be a LOONG context</strong> — a lot of tokens ! What are the other options? ( Answer below)</li></ol><p>2. <strong>Existing </strong>recommender systems already have <strong>collaborative filtering </strong>embeddings for users. We want to directly <strong>re-use</strong> them in our LLM recommender engine — as long term context. But how do we do that ?</p><p>3. They use Spotify’s previous on Embedding-to-Prefix( 2025) approach: train a 2 layer MLP to project the user embedding into LLM dimension — which produces a <strong>single token</strong> ( “soft prompt token”) to be appended at the start of query (No — we are not adding it to multiple layers, unlike Prefix-tuning(Stanford 2021) which is the key inspiration behind this)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*rgVh-fPhTK8tIOsRJZRm-A.png" /><figcaption>Source -&gt; GLIDE</figcaption></figure><p>4. Lastly, the model is trained on instruction following : given the “soft prompt”, recent history &amp; Task instruction ( what type of content) — the model generates SIDs for recommended episodes.</p><p>Model size — up to ~1B.</p><h3>2026, 21 Aug → GenRec: An LLM-Backed Recommendation Ranker at Netflix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*EQb6K6G9wzuTmKdqSCZOsg.png" /><figcaption>Source — GenRec/Netflix paper</figcaption></figure><p><strong>Phase1 training</strong> : domain adaptation of the <strong>Decoder Only model</strong> on netflix catalog +user history. It is not explicitly mentioned — we can guess it is trained via Next token prediction.</p><p><strong>For Phase2 post-training</strong>, the user-system interaction is framed as a typical Human-Chatbot conversation : context, profile, history &amp; task becomes the User Message, the user’s actual reaction becomes the Assistant Message, where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*M8wP4MW01tLD0wtBHsL8-w.png" /><figcaption>Source — GenRec/Netflix</figcaption></figure><p>The paper goes into great detail on how they compress which sort of details to what extent ( emphasize long-duration plays &amp; thumbs up, ignore noisy views/clicks, summarize repetative behaviour, prioritize recency etc. )to minimize the token spend to<strong> 1/3rd of the original context</strong>.</p><p>TRAINING :</p><p>This Decoder only model<strong><em> (~1B to ~10 B)</em></strong> is trained on 2 objectives :</p><ol><li>recommendation ranking objective — ranking head should give a higher score to the items having high engagements and vice versa. When the catalog is too large to score, sampled softmax is used instead.</li><li>language modeling /predicting tokens</li></ol><p>RL ALTERNATIVE: They also tried to expeirment with GRPO and saw some improvement — but kept it for later experiments due to the training overheads. So they came up with a cheaper alternatives. They give more or less weightage to each trainig example depending on multiple criteria using a few off-the-shelf reward models — which helps them encourage things like business constraints ( e.g. conent mixing / exposure fairness) and maximizing long term user satisfaction &amp; retention ( rather than short term binge watching — Yes, they thought really deeply on this !!)</p><p>INFERENCE: only the ranking task.</p><p>Thus, this is is a variation of “Prefill only” architecture (i.e. LLMs being used for discriminative tasks) — which can be thought of been introduced by PrefillOnly paper(2025). But whereas GenRec has a spcial scoring head used to score each item, the latter has a normal head, but outputs only one token.</p><p><strong><em>Performance </em></strong>: As tested on 10% of Netflix traffic for 4 weeks, GenRec was able to get 1.6% higher <a href="https://en.wikipedia.org/wiki/Mean_reciprocal_rank">MRR </a>( Mean Reciprocal Rank) with<strong> 40x less </strong>Phase 2( labelled) <strong>data </strong>as compared to the production model. Just as a refresher. MRR talks about how relevant the recommendations are, the initail recommendations being given more weightage ( as you can imagine, the user may give most importance to the very first recommendation, then the 2nd and so on… )</p><p>That’s all for today ! Please comment below if you think I missed any key details about the above algos that can help the other readers.</p><h3>References :</h3><ol><li><a href="https://developers.google.com/machine-learning/recommendation/collaborative/basics">https://developers.google.com/machine-learning/recommendation/collaborative/basics</a></li><li><strong>DeepMind/ NeurIPS 2023, TIGER</strong>: Shashank Rajput et al. 2023. <strong>Recommender systems with generative retrieval</strong>. In Proceedings of the 37th International Conference on Neural Information Processing Systems (New Orleans, LA, USA) (NIPS ’23). Curran Associates Inc., Red Hook, NY, USA, Article 452, 17 pages</li><li>Jiaxin Deng et al. <strong>2025</strong>. <strong>OneRec</strong>: Unifying Retrieve and Rank with Generative Recommender and Iterative Preference Alignment. arXiv:2502.18965 [cs.IR] <a href="https://arxiv.org/abs/2502.18965">https://arxiv.org/abs/2502.18965</a></li><li>Ruining He et al. 2026. <strong>PLUM</strong>: Adapting Pre-trained Language Models for Industrial-scale Generative Recommendations. In Proceedings of the ACM Web Conference <strong>2026 </strong>(United Arab Emirates) (WWW ’26). Association for Computing Machinery, New York, NY, USA, 8093–8104. doi:10.1145/3774904.3792802</li><li>Edoardo D’Amico et al. <strong>2026. Deploying Semantic ID-based Generative Retrieval for Large-Scale Podcast Discovery at Spotify</strong>. arXiv:2603.17540 [cs.IR] <a href="https://arxiv.org/abs/2603.17540">https://arxiv.org/abs/2603.17540</a></li><li>2026 , 21 Aug: <strong>GenRec</strong>: An LLM-Backed Recommendation Ranker at Netflix</li><li><a href="https://netflixtechblog.com/genrec-towards-llm-native-recommendation-at-netflix-f20be6f643e3">https://netflixtechblog.com/genrec-towards-llm-native-recommendation-at-netflix-f20be6f643e3</a></li><li><strong>PrefillOnly</strong>: An Inference Engine for Prefill-only Workloads in Large Language Model Applications — <a href="https://arxiv.org/abs/2505.07203">https://arxiv.org/abs/2505.07203</a></li><li>Huber, B et al. <strong>Embedding-to-prefix:</strong> Parameter-efficient personalization for pre-trained large language models. arXiv preprint arXiv:2505.17051 (2025).</li><li>Xiang Lisa Li and Percy Liang. <strong>Prefix-tuning</strong>: Optimizing continuous prompts for generation. arXiv preprint arXiv:2101.00190, 2021.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f51689dd064b" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/from-classical-recommenders-to-llms-the-evolution-of-recommendation-systems-f51689dd064b">From Classical Recommender Systems to Generative Recommendation : A Survey of the Evolution…</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[A Deep Dive into LLM Quantization: FP32, BF16, INT8, NF4 & QLoRA]]></title>
            <link>https://medium.com/@saurad44/a-deep-dive-into-llm-quantization-fp32-bf16-int8-nf4-qlora-830ff4936f3f?source=rss-82fbcbdab085------2</link>
            <guid isPermaLink="false">https://medium.com/p/830ff4936f3f</guid>
            <category><![CDATA[qlora]]></category>
            <category><![CDATA[int8-quantization]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm-finetuning]]></category>
            <category><![CDATA[quantization]]></category>
            <dc:creator><![CDATA[Sauradeep Debnath]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 09:08:14 GMT</pubDate>
            <atom:updated>2026-03-18T20:22:11.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i-uU9JQOMwe6k62t.jpg" /><figcaption>source : The Matrix (1999). Today’s article is all about how to store a matrix of weights with fewer bits.</figcaption></figure><p>Large Languaage Models are extremely <strong>memory </strong>intensive and often require hundreds of GBs of GPU memory for training/fine tuning ( and for inference too). Just to give you an estimation, just for a 8 billion parameter model with FP16 precision( medium sized/small-ish model by 2026 standards) requires 24–27 GB GPU memory for inference ( weights, KV cache, buffer) and 84- 128 GB for full fine tuning ( weights, activations, Adam states, gradients) . Of course, you can lower the GPU memory requirements by activation checkpointing , offloading to CPU etc. But still the numbers are still sky-high, especially for a bigger model ( say 70 B model).</p><p>Quantization techniques can help here. By reducing the numerical precision to represent the model weights, while preserving most of the model’s performance.</p><p>In this article, we will try to understand how various numerical precision formats are used in LLM <strong>quantization</strong>, why we need them and how do they actually work. Lastly we will explore the interesting properties of the NF4 quantization- a key innovation introduced in the <strong>QLoRA </strong>paper, along with why there were the need for techniques like blockwise quantization, Double quantization, quantile quantization etc .</p><p>And before that, of course, a quick recap of <strong>LoRA </strong>— which again, drastically reduces the memory &amp; computation for LLM training. E.g. as mentioned in the LoRA paper[12], Without any additional latency, LoRA was able to slash the number of trainable parameters of GPT-3 model ( which had 175B params) by a multiplier of 1/10,000 &amp;GPU memory requirements by 1/3.</p><p>We finally end today’s discussion with a sneak peek of QA-LoRA.</p><h3>Section 1 : Floating Point Representations :</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*t78ncDYLyJSH0bdLjlybIA.png" /><figcaption>Fig1 : Source — <a href="https://www.doc.ic.ac.uk/~eedwards/compsys/index.html">https://www.doc.ic.ac.uk/~eedwards/compsys/index.html</a></figcaption></figure><p>In high school, we mostly used the decimal scientific notation with a power of 10. E.g. a number like x.yz * 10^(m) where x.yz is the Mantissa , e is the Exponent . Here x,y,z can be any numbers from 0 to 9. E.g. 30 as 3 *10, 3000 as 3 *10³ .</p><p>Note that it is the Exponent that decides the range, while Mantissa decides the precision ( how precisely we are quantifying something). For example, a number 3.456 is more precise than 3.45 and so on.</p><p>For computer arithmatics, on the other hand, we use <strong>binary </strong>formats like FP32, BF16 etc.</p><p>This has a format of x.yz *2^(e). Here x, y, z can be either 0 or 1. e can be any binary number.</p><h4><strong>FP32 ( “Single Precision”) :</strong></h4><p>8 bits for exponent, 23 for mantissa 1 bit for sign ( value 1 for negative numbers).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*J-JSJ0mNXkae9db9DtSnMA.png" /><figcaption>Fig2 : <a href="https://gateoverflow.in/399276/gate-cse-2023-question-35">https://gateoverflow.in/399276/gate-cse-2023-question-35</a></figcaption></figure><p><strong>NOTE </strong>: There is another catch here. You may recall that there have been different ways to represent <strong>negative </strong>binary numbers- but <strong>2’s complement</strong> is the standard way to go it. Here you basically invert all bits and add 1 for a negating a number. This simplifies <strong>logical circuits</strong> ( same circuits for positive &amp; negative numbers).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*3tc9B4wdECR69zHkL0xRRQ.png" /><figcaption>Fig 3 : 2’s complement used for Exponent</figcaption></figure><p>However, when storing negative exponents it can be a problem for Floating point representations — especially for Bitwise <strong>comparisons </strong>— smaller numbers may appear larger , as in the above picture. Hence, a <strong>bias </strong>is added to handle this. For FP32, a bias of +127 is used. So (-1) becomes 126 , +1 becomes 128.</p><p>This bias is usually 2^(k-1) -1 for a k exponent bits. here, for 8 bits, the bias added is 2^(8–1)-1 = 2⁷-1 = 128–1 = 127.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6bfwR_DJgonw4hCuzuuPg.png" /><figcaption>Fig 4 : Source — <a href="https://www.doc.ic.ac.uk/~eedwards/compsys/float/">https://www.doc.ic.ac.uk/~eedwards/compsys/float/</a></figcaption></figure><p>For more details of the above concepts as well as binary addition/multiplication, please check out the above link by Imperial College London. ( also <a href="https://www.doc.ic.ac.uk/~eedwards/compsys/7-8_Slides_Float.pdf">https://www.doc.ic.ac.uk/~eedwards/compsys/7-8_Slides_Float.pdf</a> )</p><h3>Range of FP32:</h3><p>Armed with the above knowledge, we can easily calculate the range of FP32 numbers. Don’t worry, this is the only section with calculations and I promise it will be useful later.</p><p>For FP32, the exponent is in the range E∈{1,2,…,254}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*9RqH8UQDb_MTPoQssdrLlQ.png" /><figcaption>Fig 5: format of FP32</figcaption></figure><p>Let’s find the largest FP32 number.</p><p>Step1 : largest stored exponent =254. Largest actual exponent = 254-bias = 254–127 = 127.</p><p>Step 2: find the largest mantissa. f = All 1’s for 23 bits.</p><p>Mathemetically, using Geometric progression we can see that f is equal to 1–2 ^(-23) . Adding the implicit one ( from Fig 5 equation ). We get the largest mantissa as 2 -2^(-23). Hence the largest FP32 number is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*T5slbFrSLsmqLTT39A84tQ.png" /><figcaption>Fig 6</figcaption></figure><p>Which is roughly equivalent to 3.4 * 10³⁸ . Similarly, we can see the smallest positive FP32 number ( before it “underflows”) is roughly 1.18 * 10^(-38) . Thus the<strong> total range of FP32 is</strong> <strong>10³⁸ to 1/10³⁸</strong> ( i.e. 10^(-38)) .</p><h3>FP16 ( “Half precision”) :</h3><p>Here, by definition, we have 1 sign bit, 5 bits for exponent, 10 for mantissa. With 5 bits we can represent decimal numbers from 0 to 31. IEEE reserves 0 for ‘subnormal’s/zeros, 31 for infinity/NaN. So 1 to 30 are used for actual exponents. As discussed for FP32, a bias is used, which is 15 here — which gives us an actual FP range of -14 to +15.</p><p><strong>Range of FP16 </strong>: Calculating like before, we see that the range is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*Q-L90nno00yihuFoIa4E3w.png" /><figcaption>FP16 : much smaller range than FP32</figcaption></figure><p><strong>Why this matters for LLMs:</strong></p><p><em>Since in deep learning, values like gradients, activations, Adam moments etc. may be vary orders of magnitude, these might </em><strong><em>overflow /underflow</em></strong><em> ( go beyond the upper/lower range of) FP16 pretty easily.</em></p><p>To handle this , in the 2018 ICLR paper “<em>Mixed Precision Training</em>”, thye mention a few workarounds, like “loss-scaling to preserve gradient values with small magnitudes”.</p><p>These methods, however have various shortcomings &amp; in general, to change a model precision from FP32 to FP16 ( to get a lighter model) one would require some extra <strong>fine tuning </strong>because of a higher overflow/underflow. ( See this 2019 paper [4] for more details ) .</p><p>Fortunately, there is a solution : BF16.</p><h3>Brain Float 16 :</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*YShmQeGUmH8GlLeSMJ1VxA.png" /><figcaption>Source : [4] : 2019 PAPER by Facebook &amp; Intel : “A Study of BFLOAT16 for Deep Learning Training:</figcaption></figure><p>It’s pretty straight forward, let’s keep the <em>same number of exponent bits</em>(i.e. 8) as FP32 in order to maintain the <strong>same </strong>dynamic <strong>range</strong>. Thus, no fine tuning is required ( after converting the model tensors from FP32 to BF16). As papers like [4] mention, this achieves the same SOTA performance as FP32, unlike FP16 which sees a performance dip.</p><p>Finally we understand why BF16 is so popular in recent LLMs.</p><h3>INT8:</h3><p>First introduced by Google in 2018([6]) and later used in NLP space in the Q8BERT model by Intel Lab in 2019 as ‘quantization-aware training during the fine-tuning phase’. The latter paper’s authors were not only able to <strong>reduce the model size by 1/4</strong> , they are also able to reduce the inference time by using integer arithmatic.</p><h3><strong>Conversion from FP32( or BF16) to INT8:</strong></h3><p>This is no longer a bit level conversion. Due to the large range ( spanning many orders of magnitudes) , we can’t do something as simple as remove the digits after the decimal point ( 3.456 → 3). Rather it is a lossy, statistical approximation. If we strip away some of the complex notations, here is how it works:</p><ol><li>We define a <em>range</em>. Often it is symmetric ( say -M to +M). Assumption: Values outside this range is rare or not important.</li><li>Given the number of quantization bits, figure out how many levels we have. Since the highest number represented by b bits is 2^b ( e.g. with 2 bits we can represent 00, 01, 10,11 → 2² = 4 levels)</li><li>Compute an uniform step size = range/levels = range/256 for INT8. Or, some other heuristics for certain cases. This is the inverse of the ‘Scaling factor’ mentioned in many papers.</li><li>Quantize the real/floating point numbers into integers by :</li></ol><p>a. divide by the step size</p><p>b. round off to integer.</p><p>Please note the above is a <strong>simplified </strong>version ( +notation) to explain the idea — different papers may use<strong> slight variations</strong>. QLoRA version is covered later in this article.</p><p>E.g. here is the Quantization scheme used in Q8BERT paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38vgFr3iMOFpSbfxMcFKRQ.png" /><figcaption>detailed quantization scheme in [7]</figcaption></figure><p>Please note :</p><p>i) the third bracket like symbol around x* S^x denotes the <strong>nearest integer function — </strong>which does the rounding as mentioned before.</p><p>ii) Q8BERT uses signed symmetric bins ( -127 to +127 instead of 0 to 256 ) hence, while calculating scaling factor, they use M (=127) instead of the number of levels( =256)</p><h3><strong>Issues with uniform binning ( INT8/INT4):</strong></h3><p>Due to the rounding off, all real numbers falling within the same bin become the same integer. Hence if the real numbers are roughly uniform, the reconstruction loss ( i.e. the MSE of original FP32 and the de-quantized FP32 ) would be minimal.</p><p>But what if that is not the case ?</p><p>In case of transformer weights, unfortunately it’s the other way. <strong>There is a strong peak at zero</strong>, while the distribution being roughly Gaussian/Laplacian( Source — QLoRA paper [8]) . So in case of uniform binning, most bins would be nearly empty, while the bins near 0 would be super crowded — thus leading to very high reconstruction loss near 0.</p><p>Things are still ok with INT8 with 256 levels. For INT4 , there are only 2⁴ =16 levels. So, the above issues take a far more severe turn.</p><h3>4-bit NormalFloat(NF4):</h3><p>That’s where NF4 from QLoRA paper comes to rescue. It uses <em>quantile quantization</em> — where each bin will have equal number of values — thus , it is information theoretically optimal for quantization.</p><p>However, the vanilla quantile quantization is expensive, and the approximations have large errors for outliers.</p><p>However the QLoRA authors found a smart solution to that. As the transformer weights are zero centred Gaussians, they scale it, and then calculate the <strong>quantiles </strong>using quantile functions of standard normal distribution N(0,1).</p><p>(Unlike INT4 which works ok during inference but breaks gradient during training /fine tuning— NF4 works just fine during finetuning.)</p><p><strong>This was one major novel concept introduced by QLoRA. The other two are Double Quantization &amp; Paged Optimizers.</strong></p><p>To understand Double Quantization, let us understand the following:</p><p>i) Blockwise k-bit quantization ii) the need for double quantization.</p><h3>Block wise k-bit quantization:</h3><p>A “vanilla” quantization into INT8 , which was discussed above, can also be expressed this way ( as mentioned in QLoRA paper) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*S1fDCta1c2VNdgErd5TA-Q.png" /><figcaption>QLoRA paper [8]</figcaption></figure><p>Where is the issue with this approach ?</p><p>What if there is very large outlier ? Then absmax(X-FP32) would be pretty large. Hence some bins would be very empty/sparse.</p><p>One way to improve the situation is to divide the entire tensor into n continuous blocks of size B each — and have a separate quantization constant for each.</p><p>Intuitively, the smaller the blocksize, the lower the quantization error ( but requires more storage).</p><h3>Need for Double Quantization:</h3><p>The above blockwise quantization creates another problem. We need to store the <strong>quantization constants for each blocks</strong> — and each constant is FP32 .i.e. requires 32 bits to store. If we flesh out the calculations given in the QLoRA paper, we get the following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*CAA6uVihXZPLs6_ScBoHdQ.png" /></figure><p>That’s a lot of extra bits ?</p><p>The solution is quite intuitive.</p><p>In stead of FP32, <strong>let’s store these quantization constants themselves as INT8 </strong>— thus saving 24 bits for each number. However, to quantize them, we need quantization constant ( “scale”(s)). Please recall we can decide ourselves what is the block size. Since these quantization constants are very likely to vary a lot less than the original weights/gradients/activations — let’s choose a bigger block size. For example, if we choose a block size of 256 for this 2nd level of quantization — the paper shows that now we need to store 0.127 bits per weight ( aka per parameter) instead of the previous 0.5.</p><p>This is exactly what Double Quantization is.</p><p>But before covering the rest of the concepts in QLoRA, we need a quick refresher on it’s predecessor LoRA</p><h3><strong>LoRA quick recap :</strong></h3><h3>2021 Oct, LoRA — LOW-RANK ADAPTATION OF LARGE LANGUAGE MODELS, by Microsoft / Hu et al</h3><p>While doing fine tuning, LoRA updates a extremely small number of weights as compared to the original weight counts.</p><p>The concept behind it is fairly basic linear algebra. Taking the advantage of matrix multiplication properties. So if I multiply A, a really tall matrix with M rows &amp; P columns ( M&gt;&gt;P) , with B , with a wide matrix (P rows , N columns ; N&gt;&gt;P), I can get a really big matrix C with dimensions M x N ( M &gt;&gt;P, N&gt;&gt;P)</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*PyxmLJxItARtSVTh3Qbwmw.jpeg" /><figcaption>Source : self. The matrix multiplication concept behind LoRA</figcaption></figure><p>Now let’s apply this to the Transformer architecture. We have Wk, Wv, Wq matrices ( learnt during training) which , when multiplied by input vector, gives us the key , query and value vectors — which are used for self attention computaion.</p><p>What we would do is, instead of fine tuning the entire network ( in our diagram, that would be C matrix), we keep it frozen, and instead fine tune A &amp; B matrices and add it back to C ( original model params). The small dimension P is actually called “rank” r in this context. The authors of LoRA experimented with ranks from 2 to 64 (more on this on future articles).</p><p>The QLoRA paper expresses LoRA with the following equation :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*sW_0RYWNvgj72vniUiI2-Q.png" /><figcaption>LoRA equation [8]</figcaption></figure><p>Thus L1 &amp; L2 are the low rank adapters that we will finetune and later add back to the original matrix Y= XW.</p><p>To summarize the contribution of LoRA, let us quote the 2024 ICML paper for VERA( a topic for the next article in this series) :</p><blockquote>“LoRA significantly lowers the hardware barrier for finetuning by reducing the need for gradient calculation and optimizer state maintenance for most parameters.”</blockquote><h3>QLoRA , 2023 May: Putting all the elements together:</h3><p>If we add NF4 quantization &amp; ( blockwise) Double Quantization to LoRA — we get QLoRA :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*ZHaTuiLZUm2QF0gV2omP3A.png" /><figcaption>QLoRA equations [8]</figcaption></figure><p>Salient points :</p><ol><li>QLoRA uses <strong>NF4 only for the storage</strong> of the original parameter weights. Nothing else !!</li><li>All computation is still done in BF16.</li><li>Please note : for forward &amp; backward pass, only the adapters are trainable — but we need the original weights too ( as read only/frozen). How do we get them back to BF16 ? Ans : we de <strong>quantize </strong>them.</li></ol><p>Same thing at inference time, by default. That’s also the standard way to do it with huggingface. Please check out this notebook from huggingface for more details — <a href="https://colab.research.google.com/drive/1VoYNfYDKcKRQRor98Zbf2-9VQTtGJ24k?usp=sharing">https://colab.research.google.com/drive/1VoYNfYDKcKRQRor98Zbf2-9VQTtGJ24k?usp=sharing</a></p><p>Some key steps from the notebook :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1GNy4niePKEMIt8sk0tNw.png" /><figcaption>HF notebook code- 1 : Load the original Model but in k-bit Precision</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RGXgLieq2C7zmDyp2TZCQ.png" /><figcaption>HF notebook code-2 : Preprocessing the model before the fine-tuning : freezes the base model ; converts all Normalization layers to FP32 as these are highly sensitive to errors ; enables gradient checkpointing etc.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*7jzIC5a-9H8oUk_IU6oE5Q.png" /><figcaption>HF Notebook code -3. NOTE — we are not merging them back to the original model . That is done via merge_and_unload() — and is usually avoided.</figcaption></figure><p>( Alternatively, you can merge back the adapters to FP32 or BF16 original model post training, pre deployment — but it may cause precision loss &amp; memory overhead).</p><p>Hope you now understand the entire QLoRA equation.</p><p><strong>One final piece of QLoRA : </strong>Memory Requirements for Activation Gradients- <strong>Paged Optimizer :</strong></p><p>What if the GPU runs out of memory ? Using NVIDIA unified memory feature, Paged Optimizers can transfer data between CPU &amp; GPU page-by-page.</p><p>Experimental results :</p><p>i) NF4 outperforms INT4</p><p>ii) QLoRA performance is almost as good as LoRA , much lower storage.</p><h3>What’s next ?</h3><h3>Sneak peek for : Quantization Aware LoRA (QA-LoRA) -2023 Sept:</h3><p>Now we come to the last topic for today : QA-LoRA.</p><p>Why do we need QA-LoRA ?</p><p>So QLoRA, its predecessor quantized the model weights, thus saving compute time &amp; memory at training time. However, at inference time we need to dequantize the weights back to BF16 which adds some extra lag. Thus QLoRA inference is SLOW.</p><p>Additionally, as pointed in the QA -LoRA paper, since NF4 is totally unique format, so the kernel/hardware optimizations for low precision arithmatic with it did not exist at time ( not much progress even till date). So even QLoRA finetuning ( and inference) is terribly slow ( Even though the main computation in QLoRA is done in BF16, there are other operations with NF4). To sum it up, let us quote the QLoRA paper :</p><blockquote>“the only benefit brought by QLoRA is the reduced memory cost for fine-tuning.”</blockquote><p>What if we needed a smaller, quantized model, say for an edge device without this added latency ( and where the final model has a very small size) ?</p><p>We could try Post Training Quantization ( PTQ) post QLoRA, but turns out it leads to a <em>huge accuracy loss</em>.</p><p>QA-LoRA resolves these 2 issues. The compute is optimized ( i.e. faster training &amp; inference) using the well known INT4 format; the final finetuned LLM is in a quantized format — perfect for edge device deployment — and they significantly improve the quantization loss by balancing the degrees of freedom of the quantization and LoRA. The last part is the topic for another day !</p><p>As Arnold says, Hasta la vista; that’s all for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T5X49oFZkI0hcFrt.jpg" /><figcaption>Terminator 2 movie</figcaption></figure><h3>References:</h3><ol><li><a href="https://www.puntoflotante.net/FLOATING-POINT-FORMAT-IEEE-754.htm">https://www.puntoflotante.net/FLOATING-POINT-FORMAT-IEEE-754.htm</a></li><li>ICL, UK : <a href="https://www.doc.ic.ac.uk/~eedwards/compsys/float/">https://www.doc.ic.ac.uk/~eedwards/compsys/float/</a> ; <a href="https://www.doc.ic.ac.uk/~eedwards/compsys/7-8_Slides_Float.pdf">https://www.doc.ic.ac.uk/~eedwards/compsys/7-8_Slides_Float.pdf</a></li><li>Micikevicius, P., Narang, S., Alben, J., Diamos, G., Elsen, E., Garcia, D., … &amp; Wu, H. (2017). <strong>Mixed precision training</strong>. <em>arXiv preprint arXiv:1710.03740</em>.</li><li>Kalamkar, D., Mudigere, D., Mellempudi, N., Das, D., Banerjee, K., Avancha, S., … &amp; Dubey, P. (<strong>2019</strong>). <strong>A study of BFLOAT16 for deep learning training</strong>. <em>arXiv preprint arXiv:1905.12322</em>.</li><li>Kurtic, E., Marques, A. N., Pandit, S., Kurtz, M., &amp; Alistarh, D. (<strong>2025</strong>, July). “Give Me BF16 or Give Me Death”? Accuracy-Performance Trade-Offs in LLM Quantization. In <em>Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)</em> (pp. 26872–26886).</li><li><strong>INT8</strong> : Jacob, B., Kligys, S., Chen, B., Zhu, M., Tang, M., Howard, A., … &amp; Kalenichenko, D. (<strong>2018</strong>). Quantization and training of neural networks for efficient integer-arithmetic-only inference. In <em>Proceedings of the IEEE conference on computer vision and pattern recognition</em> (pp. 2704–2713).</li><li>Zafrir, O., Boudoukh, G., Izsak, P., &amp; Wasserblat, M. (<strong>2019</strong>, December). <strong>Q8bert</strong>: Quantized 8bit bert. In <em>2019 Fifth Workshop on Energy Efficient Machine Learning and Cognitive Computing-</em><strong><em>NeurIPS</em></strong><em> Edition (EMC2-NIPS)</em> (pp. 36–39). IEEE.</li><li>Dettmers, T., Pagnoni, A., Holtzman, A., &amp; Zettlemoyer, L. (<strong>2023</strong>). <strong>Qlora</strong>: Efficient finetuning of quantized llms. <em>Advances in neural information processing systems</em>, <em>36</em>, 10088–10115.</li><li>Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA <a href="https://huggingface.co/blog/4bit-transformers-bitsandbytes">https://huggingface.co/blog/4bit-transformers-bitsandbytes</a></li><li><a href="https://colab.research.google.com/drive/1VoYNfYDKcKRQRor98Zbf2-9VQTtGJ24k?usp=sharing">https://colab.research.google.com/drive/1VoYNfYDKcKRQRor98Zbf2-9VQTtGJ24k?usp=sharing</a></li><li>Xu, Y., Xie, L., Gu, X., Chen, X., Chang, H., Zhang, H., … &amp; Tian, Q. (2023). Qa-lora: Quantization-aware low-rank adaptation of large language models. <em>arXiv preprint arXiv:2309.14717</em>.</li><li>Hu, E. J., Shen, Y., Wallis, P., Allen-Zhu, Z., Li, Y., Wang, S., … &amp; Chen, W. <em>LoRA: Low-Rank Adaptation of Large Language Models (Oct 2021)</em>. arXiv preprint arXiv:2106.09685.</li><li>ChatGPT/Gemini screenshots with mathematical illustrations : used to generate illustrations &amp; examples to better explain various concepts in the above research papers. ( wherever no other source is cited for screenshots). However all non-screenshot texts are self-authored.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=830ff4936f3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RL for LLM Reasoning : TD, GAE, PPO, GRPO, DeepSeekMath  & DeepSeek R1]]></title>
            <link>https://blog.gopenai.com/rl-for-llm-reasoning-td-gae-ppo-grpo-deepseekmath-deepseek-r1-9b42dc065a5a?source=rss-82fbcbdab085------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b42dc065a5a</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[proximal-policy]]></category>
            <category><![CDATA[deepseek-r1]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[grpo]]></category>
            <dc:creator><![CDATA[Sauradeep Debnath]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 05:04:20 GMT</pubDate>
            <atom:updated>2025-10-02T08:11:04.960Z</atom:updated>
            <content:encoded><![CDATA[<h3>RL for LLM Reasoning : TD, GAE, PPO, GRPO, DeepSeekMath &amp; DeepSeek R1</h3><p>It’s been over a month since DeepSeek R1 came out — which performs as good as openai-o1–1217 in reasoning. Much of its success can be attributed to its scalable RL. To understand the magic behind its feats- let’s start at the basics.</p><p>The main topic of discussion here is GRPO, introduced in the DeepSeekMath paper [5]. The authors list 3 papers as pre requisites — <strong>GAE, PPO &amp; InstructGPT </strong>. Let’s try to go through them all</p><p>Some of the topics discussed here, have been discussed in greater depth in the RL <a href="https://medium.com/@saurad44/reinforcement-learning-part-1-model-based-model-free-function-approximation-4501e317e9d6">part 1</a> &amp; <a href="https://medium.com/gopenai/policy-based-deep-rl-part-2-of-reinforcement-learning-series-cdca33709ea2">part 2</a> blogs of mine. <em>I will highly encourage the readers to briefly go through them first, especially for the definitions like Value functions and Bellman equation.</em></p><ol><li><a href="#edaa">Recap : TD — Temporal Difference</a></li></ol><p>2. <a href="#1bd8">RECAP : Policy Gradient</a></p><p>3. <a href="#1875">Generalized Advantage Estimate (2015)</a>:</p><p>4. <a href="#d807">Actor Critic Method</a></p><p>5. <a href="#e922">PPO paper (OpenAI, 2017)</a></p><p>6. <a href="#98d2">InstructGPT (2022) : Using PPO for RLHF</a></p><p>7.<a href="#44a9"> DeepSeekMath(2024) : introducing GRPO</a></p><p>8. <a href="#c829">DeepSeek R1(2025, Jan)</a></p><h3><strong>1. Recap : TD — Temporal Difference :</strong></h3><p>TD methods can learn directly from raw experience, ( of interaction with the “environment” ) just like Monte Carlo methods, without the need for the knowledge of the environment’s dynamics ( transition probability P(S’|S) &amp; reward function R(s)).</p><p>But on the other hand, just like DP, we will update the estimate of the “goodness”(Value Function) of state S based on the available information we have regarding the other states. Thus the TD methods can be implemented in an <strong>online</strong>, incremental method , unlike Monte Carlo . The update formula uses the below result from incremental definition of mean :</p><p><em>New Estimate = Old Estimate + Learning Rate(Target — Old Estimate) </em>→ Eq(1)</p><p>The derivation is pretty straightforward, covered in my first <a href="https://medium.com/@saurad44/reinforcement-learning-part-1-model-based-model-free-function-approximation-4501e317e9d6">RL blog.</a></p><p>Here via bootstrapping, once we take an action at state S and move to a new state S’ and get reward R, we want to update the value function V(S) i.e. “<em>goodness of state S</em>” by incorporating the knowledge of the new reward R we have just got.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*HF3ZsBe_wogrnrEAZ10ftA.png" /><figcaption>Sutton &amp; Barto [1]</figcaption></figure><p>Since Vπ(S) = E[R+ γVπ(S’)] → we can <em>sample</em> R+γVπ(S’) to get an estimate for Vπ(S). But since the <em>true</em> value function of state S’ is not known either, we will settle for our current estimate of S’ i.e. V(S’).</p><p>Here it is worth mentioning that TD ( &amp;MC) are called <em>Sample backups</em> , unlike DP which is a <em>full backup</em> — because we are using a single sample ( successor /next state S’ ) to update the current value function estimates ( i.e. V(s) ), in stead of looking at all possible successors and their probability distributions ( as done in DP)</p><p>The full TD algorithm in the case where <strong>we want to update the estimate after taking a single step</strong> ( TD[0] algo) is described below : ( Note how we are using Eq(1) defined above here )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/0*h3EWPsnlfDbY2tK-.png" /><figcaption>Sutton &amp; Barto [1]</figcaption></figure><p>We can update the estimates not just after one step — but it can also be after any n steps (“n step TD”). We can even average the returns for multiple values of n( e.g. an weighted average of 1, 2, 3 &amp; 4 step returns) . One such algorithm, called<strong> TD(λ)</strong>, weights the returns by λ raised to the power of (n-1), λ Є [0,1] ; thus giving the highest weightage to the one-step return.</p><h3><strong>2. RECAP : Policy Gradient :</strong></h3><p>GAE builds up on the idea of Policy Gradient algorithm presented in detail in <a href="https://medium.com/@saurad44/policy-based-deep-rl-part-2-of-reinforcement-learning-series-cdca33709ea2"><em>Part 2 of my RL blog </em></a><em>. </em>The general idea behind Policy based RL is the following : We want to <strong>find the optimal stochastic policy</strong> π* (θ) which maximizes the loss function J(θ) = Vπ(θ). Hence we want to<strong> ascend the loss landscape</strong> by changing the parameter θ by Δ θ =α ∇ J(θ) (where ∇ → gradient, α — step size parameter).</p><p>After doing some simple algebra and replacing the expectation with average ( to get a model free /sample based estimate), we get :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*FbfLB6rs2QLP3j4A.png" /><figcaption>IIT Hyd Classnotes [8]. Here 𝜏 denotes the trajectory i.e. the s0, a0, s1, a1,… etc. sampled from policy π(θ)</figcaption></figure><p>Policy Gradient adds two minor tweaks to reduce the variance of the above process :</p><ol><li>Policy at time t cannot influence the rewards from the past, so let’s ignore them</li><li>Let’s deduct a baseline from the rewards to get zero mean rewards — without impacting the gradient directions. There are multiple options for it. As the GAE paper explains, using Advantage function gives the lowest variance option.</li></ol><p>As a recap, Aπ(s,a) = Qπ(s,a) — Vπ(s). Thus Advantage function tells us how much better or worse is taking a particular action A( among all other possible actions), when we are at state S.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*hiVZFO1I1El4aM1Y.png" /><figcaption>Vanilla PG algorithm : source : IITH notes [8]</figcaption></figure><p>Since the true advantage Aπ is not known ( neither are Qπ or Vπ), GAE gives a way of estimating this advantage function, using TD algorithm.</p><h3>3. Generalized Advantage Estimate (2015)[6]:</h3><p>As the authors of GAE mention in the paper abstract, the key contribution of GAE algo is reducing the variance in policy gradient estimates.</p><p>Now, if we define a TD residual of the state value function V(s) with discount γ → ie. <strong>δ(t) = R(t) + γ V(s, t+1)- V(s,t)</strong> and take its expectations, we can see that :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*hpL9SHzEQ81fbsAjvm-xmg.png" /><figcaption>GAE paper[6]</figcaption></figure><p>Since, once again, we do not have the correct/true value function Vπ(s), we have to estimate Aπ(s,a)</p><p>Now, as we discussed in case of TD, it can be either 1-step ( update the value functions after every transition) or k-step. Let us get the TD residuals for k-step here :( with the value of k being 0 to infinity)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*FwoZ_lzetbl-L7I8_q2p3A.png" /><figcaption>GAE paper [6]</figcaption></figure><p>If we do an exponentially weighted average of all these k-step TD estimators , with lower weightage for a higher k — &gt; We get GAE estimators for Advantage function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_WbPFz2dCdX1HATiwboxA.png" /><figcaption>GAE paper [6]</figcaption></figure><p>NOTE : From the above formula, to calculate the above Advantage Estimate, we need <strong>δ(t) </strong>which is , by definition,<strong> R(t) + γ V(s, t+1)- V(s,t). Thus, value function estimation is extremely important for GAE.</strong></p><p>NOTE — <em>PPO</em> uses this GAE in its implementation.</p><p>Understanding the above is crucial to understand &amp; appreciate the brilliance &amp; innovation of <em>GRPO</em>.</p><h3>4. Actor Critic Methods :</h3><blockquote>“Actor-critic methods are TD methods that have a <strong>separate memory structure</strong> to explicitly represent the policy independent of the value function. The policy structure is known as the actor, because it is used to select actions, and the estimated value function is known as the critic, because it criticizes the actions made by the actor.”- Sutton &amp; Barto</blockquote><p>It is a on-policy learning algo as the critic is analyzing the policy currently followed by the actor. Every time the actor takes an action — the ctitic analyzes how good or bad that action was given the current state — “whether things have gone better or worse than expected.” This judgement takes the form of a<strong> TD error : δ = R + γV(s’) — V(s)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*EHTJq8si3OwV1thiyne2gg.png" /><figcaption>Sutton &amp; Barto[1]</figcaption></figure><p>Thus the general form of batch actor critic would be the following. Please note that for online setting , in stead of fitting Vπ, we would be merely updating Vπ(s) using the target R+Vπ(s’):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*grMep5KXdv06WwXS2VL8Fg.png" /><figcaption>Batch Actor Critic : CS 285 at UC Berkeley[2]</figcaption></figure><h3>5. PPO paper (OpenAI, 2017)[7]:</h3><p>Here’s quick refresher on the journey from NPG to PPO from my <a href="https://blog.gopenai.com/policy-based-deep-rl-part-2-of-reinforcement-learning-series-cdca33709ea2"><em>RL blog 2</em></a> :</p><p><strong>NPG</strong> → Takes account of step sizes in the policy space as opposed to vanilla PG — where it was very difficult to get the step size right. Uses KL Divergence/ Fisher information matrix.</p><p><strong>TRPO</strong> → Builds up on NPG — The TRPO paper mentions their main contribution is theoretically proving that minimizing a certain surrogate objective function can lead to guaranteed policy improvement with <em>non-trivial ( </em><strong><em>large enough) step sizes</em></strong>. Then they suggest a series of approximations for the practical implementation of the algorithm. This algorithm is <strong>scalable</strong> and hence can handle policies of tens of thousands of parameter ( it was very challenging at that time)</p><p><strong>PPO</strong> → Both NPG and TRPO use 2nd order information ( Fisher matrix). PPO does not and thus <em>simplifies the computation</em>.</p><p>PPO can be implemented as Actor Critic : if we have fixed length trajectories. For each iteration N independent actors collect T timestamps of data — and then with that data, we optimize the surrogate loss with Mini batch SGD or Adam.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*2LR5mV2ghBIfyPj_dS0kAA.png" /><figcaption>PPO[7]</figcaption></figure><p><strong>But what is this surrogate loss in case of PPO ?</strong></p><p>Let us try to recap the basics. They introduced 2 new surrogate loss functions in their paper :</p><ol><li><strong>Clipped Surrogate Objective</strong> :</li></ol><p>So, PPO maximizes the below objective :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/0*kkSPAhBK9OLE5XPu.png" /><figcaption>PPO paper [7]</figcaption></figure><p>where rt(θ) is the probability ratio :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*4rP37HZBZnNLtCZM.png" /><figcaption>PPO paper [7]</figcaption></figure><p>But without any constraint , we could have very huge policy updates, hence they propose this new surrogate objective, penalizing whenever the old and new policies become too different, by clipping the probability ratio between 1+Є and 1-Є :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iCugtLSI1nN50-dr.png" /><figcaption>PPO paper [7]</figcaption></figure><p>NOTE — TRPO ( PPO’s predecessor) implements the same constraints between θ &amp; θ-old via KL divergence.</p><p>If we plug-in the last few equations together — We get the formula of PPO that is there in the DeepSeekMath paper[5].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*BVLGiSLkKpyOB3TKr00YwQ.png" /></figure><p><strong>2</strong>.<strong> Adaptive KL Penalty</strong> : Same idea about comparing new &amp; old policy but using KL divergence. Note that they mentioned this<em> fared worse than clipped objective</em> ; and that this could be used independently or in conjunction with the former. <em>Let’s skip this for now.</em></p><p><strong>Final algorithm</strong> : They augment the CLIP loss to arrive at the final objective, would like to simply quote them directly :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TGc2cjmxuAcXJ_l0.png" /><figcaption>PPO paper [7]</figcaption></figure><h3>6. InstructGPT (2022)[9] : Using PPO for RLHF :</h3><p>So we understand PPO now. But how do we use for aligning an LLM to human preference ? That’s when the authors of DeepSeekMath turned for inspiration to the InstructGPT paper.</p><p>Key ideas/components :</p><p>i) the supervised fine tuned (SFT) model —GPT-3</p><p>ii) Reward Model ( RM) — trained on labeller inputs ( corrected for user bias). The “value function” is initialized from RM. They use 6B model for both.</p><p>iii) RL — Given a random prompt, the SFT model gives a response. Based on both prompt &amp; response, the RM gives a reward.</p><p>iv)Lastly they mentioned that they “add a per-token KL penalty from the SFT model at each token to mitigate over-optimization of the reward model.”[9]</p><p>The core idea being, we are imposing some penalty when the learn RL policy diverges too much from the (original) SFT model ,so as to prevent <a href="https://www.coursera.org/lecture/generative-ai-with-llms/rlhf-reward-hacking-Cux3s">reward hacking. </a>[10]. So, basically we don’t the new LLM to ‘cheat’ the reward system of RM, by outputting over-positive things that probably aren’t the right response to the input prompt.</p><p>As I was reading this concept, <em>my first thought was : wait , didn’t we already do it in PPO with the ratio clipping ?</em> Answer : that was the policy comparison between n-th and (n+1)th step of RL ( which had parameters <strong>θold) </strong>. Here, we are comparing 0-th ( before RL) &amp; n-th step.</p><p>The combined objective function in RL for them is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*yFdOem2waVioelXFZgmSgA.png" /><figcaption>InstructGPT paper [9]</figcaption></figure><p>Here rθ(x,y) is the scalar reward from the RM with parameter θ for prompt x and completion y. If you are like me, you probably might not be sure how the above is KL divergence penalty. Hopefully, the below mathematical relation will help :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*nS-ZYd7Wd7DHjasuKgQuAQ.png" /><figcaption>source : <a href="https://stats.stackexchange.com/questions/642122/expectation-of-kl-divergence-only-as-the-log-ratio-of-the-probabilities">stats stackexchange</a> [11]</figcaption></figure><h3>7. DeepSeekMath(2024) : introducing GRPO</h3><p>Before discussing the actual GRPO implementation, let us put the above combined reward formula of InstructGPT in the notations of DeepSeekMath paper , for the sake of uniformity of syntax :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGR-Bs8RXcyq4_vkuVQeUg.png" /><figcaption>source : DeepSeekMath [5]</figcaption></figure><p>Now let’s try to dissect the core ideas related to GRPO, step by step :</p><ol><li>When we studied Policy Gradient , we got to know we need a baseline to reduce the variance — one very good baseline is Advantage function</li><li>We got to know in GAE, we can estimate the Advantage function using Value functions</li><li>For Actor Critic algorithms ( e.g. PPO) , the <em>actor</em> is the policy, while the value function is the <em>critic</em>.</li><li>DeepSeekMath highlights the fact that in PPO, both of these policy &amp; value functions are of comparable size — which requires a lot of memory &amp; computation</li><li>to mention an added difficulty : “While in the LLM context, usually only the last token is assigned a reward score by the reward model, which may complicate the training of a value function that is accurate at each token.”[6]</li><li>Anyway, for the above reason, GRPO suggests, what if we could get the baseline not from Value function estimates ( like GAE) , but rather than from the average reward of a bunch of outputs o(1) to o(G) for the same prompt for the old policy <strong>θold ?</strong></li></ol><p>Here, by the maximizing the following objective, we can get the optimized policy :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvxasOF13Jx_F-SGp9C1XA.png" /><figcaption>GRPO formula, using average group reward as baseline [5]</figcaption></figure><p>Here the advantage function estimate of a token Â is calculated by ‘normalizing’ the reward i.e. (reward — mean group reward )/ group reward standard deviation. Rewards, as usual, are scored by an RM.</p><p>7. In InstructGPT, the KL-penalty was using the policy rewards, now it is just estimated from group output rewards :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*pbHJRiwa39_fYOtrvY4Chg.png" /><figcaption>GRPO [5]</figcaption></figure><p>8. Finally, to specifically help with complex mathematical reasoning, they provide reward at the end of each reasoning step, not just final output ( also normalized like point 6)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Km3PPU5q8mTWGLXCb7OfTg.png" /><figcaption>Source : DeepSeekMath[3] — Value Model is no longer used</figcaption></figure><h3>8. DeepSeek R1(2025, January )</h3><p>So, they trained two models — DeepSeekR1- Zero and DeepSeek R1 — the former without any supervised fine tuning , just RL using GRPO — and thus had poor readability issues &amp; mixing up different languages. Below benchmark shows its performance compared against OpenAI’s o1 ( which can further improved via majority voting, in case of R1-Zero.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*YeTcpP9Ph6mVOSiDgfyIgQ.png" /><figcaption>DeepSeek-R1-Zero paper [4]</figcaption></figure><p>DeepSeek-R1-Zero had two kinds of rule-based rewards :</p><ol><li>Accuracy rewards</li><li>Format rewards : forcing the model to put its thinking process between &lt;think&gt; and &lt;/think&gt; tokens</li></ol><p>“Self evolution process” : Just from RL, this model learnt that re-evaluating its initial approach can lead to better reasoning power.</p><blockquote>“Behaviors such as reflection — where the model revisits and reevaluates its previous steps — and the exploration of alternative approaches to problem-solving arise spontaneously. These behaviors are not explicitly programmed but instead emerge as a result of the model’s interaction with the reinforcement learning environment.” [4]</blockquote><p><strong>DeepSeek-R1</strong> : Before RL, they did a supervised fine tuning on a small set of long CoT. Some salient features :</p><ol><li>They introduced a language consistency reward to discourage language mixing</li><li>Post RL for Reasoning with rule based reward scenario, there is a 2-epoch SFT step using DeepSeek V3 pipeline with both reasoning non reasoning data — the latter for general capability like factual QA, translation etc.</li><li>finally a secondary RL stage, — Here, reasoning tasks are rule based, as before, while for helpfulness &amp; harmlessness, they use a reward model to capture the complexity of human preference</li><li>Other experiments — they realized for smaller models, just distilling on DeepSeek-R1 is not only the cheaper alternative, but also could lead to the improved performance.</li><li>Failed experiments — a) Process Reward Models</li></ol><p>b) <em>Monte Carlo Tree Search</em> — yes, I was surprised to see too that MCTS did not work. They attribute the failure to exponentially large search space for token generation as well as the difficulty of training a fine grained Value function that is required for MCTS.</p><p>But MCTS is the topic for another day. Good bye for now !</p><h3>References :</h3><ol><li>“<a href="http://incompleteideas.net/book/the-book-2nd.html">Reinforcement Learning: An Introduction</a>” — Richard S. Sutton and Andrew G. Barto</li><li><a href="https://rail.eecs.berkeley.edu/deeprlcourse-fa20/">Deep Reinforcement Learning</a> , CS 285 at UC Berkeley</li><li>Jin, P. H., &amp; Keutzer, K. (2015). Convolutional monte carlo rollouts in go. <em>arXiv preprint arXiv:1512.03375</em>.</li><li>Guo, D., Yang, D., Zhang, H., Song, J., Zhang, R., Xu, R., … &amp; He, Y. (2025). <strong>DeepSeek-R1</strong>: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning. <em>arXiv preprint arXiv:2501.12948</em>.</li><li>Shao, Z., Wang, P., Zhu, Q., Xu, R., Song, J., Bi, X., … &amp; Guo, D. (2024). <strong>Deepseekmath</strong>: Pushing the limits of mathematical reasoning in open language models. <em>arXiv preprint arXiv:2402.03300</em>.</li><li><strong>GAE</strong> : Schulman, J., Moritz, P., Levine, S., Jordan, M., &amp; Abbeel, P. (2015). High-dimensional continuous control using generalized advantage estimation. <em>arXiv preprint arXiv:1506.02438</em>.</li><li><strong>PPO</strong> : 2017, “<a href="https://arxiv.org/abs/1707.06347">Proximal policy optimization algorithms</a>” by John Schulman et al</li><li>Class Notes by Dr. <a href="https://scholar.google.com/citations?user=4UB8w1AAAAAJ&amp;hl=en">Easwar Subramanian</a>, IIT Hyderabad</li><li><strong>InstructGPT</strong> : Ouyang, L., Wu, J., Jiang, X., Almeida, D., Wainwright, C., Mishkin, P., … &amp; Lowe, R. (2022). Training language models to follow instructions with human feedback. <em>Advances in neural information processing systems</em>, <em>35</em>, 27730–27744.</li><li><a href="https://www.coursera.org/learn/generative-ai-with-llms/lecture/Cux3s/rlhf-reward-hacking">https://www.coursera.org/learn/generative-ai-with-llms/lecture/Cux3s/rlhf-reward-hacking</a></li><li><a href="https://stats.stackexchange.com/questions/642122/expectation-of-kl-divergence-only-as-the-log-ratio-of-the-probabilities">https://stats.stackexchange.com/questions/642122/expectation-of-kl-divergence-only-as-the-log-ratio-of-the-probabilities</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b42dc065a5a" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/rl-for-llm-reasoning-td-gae-ppo-grpo-deepseekmath-deepseek-r1-9b42dc065a5a">RL for LLM Reasoning : TD, GAE, PPO, GRPO, DeepSeekMath  &amp; DeepSeek R1</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[Accelerating LLM Inference with efficient Self-Attention — MQA, GQA, MLA(DeepSeek), Adaptive KV…]]></title>
            <link>https://blog.gopenai.com/accelerating-llm-inference-with-efficient-self-attention-mqa-gqa-mla-deepseek-adaptive-kv-2bb48c14e798?source=rss-82fbcbdab085------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bb48c14e798</guid>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[self-attention]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Sauradeep Debnath]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 04:53:18 GMT</pubDate>
            <atom:updated>2026-09-02T19:21:30.950Z</atom:updated>
            <content:encoded><![CDATA[<h3>Accelerating LLM Inference with efficient Self-Attention — MQA, GQA, MLA(DeepSeek), Adaptive KV Caching</h3><p>Hey guys, today’s blog is all about speeding up LLM inference, with a focus on KV caching. The exact topics with internal links —</p><ol><li><a href="#76dc">Background : the recent DeepSeek V3 paper</a></li><li><a href="#df09">Recap : Multi Headed Attention</a></li><li>W<a href="#9673">hy LLM inference is serial</a></li><li>T<a href="#d4c7">he challenges of KV Cachin</a>g</li><li><a href="#3ba5">2019 — Multi Query Attention</a></li><li><a href="#ec0d">2023 May — Grouped Query Attention</a></li><li><a href="#ac23">2023 — Modified MQA in Falcon models</a></li><li><a href="#e315">2024 May — DeepSeek V2 — Multi Head Latent Attention</a></li><li><a href="#5982">FastGen : Adaptive KV caching ( ICLR 2024)</a>: the analysis of 5 Fundamental Attention Structures — the first paper to do so for a decoder -only model — saving the best for the last 🤩! My personal favorite paper of the series.</li></ol><h3>Background : the recent DeepSeek V3 paper</h3><p>It all started when I started reading the DeepSeek V3 paper from Dec 27, 2024. It borrows 2 core ideas from its predecessors — Multi-head Latent Attention (MLA) from May, 2024 and DeepSeekMoE architectures, from Jan 2024 — and adds a couple of new features on top it. It performed really well, especially in various coding and mathematical benchmarks, despite its “economical training costs” of only $6 million :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SptpXH1cyhV2oJEtmpqr5A.png" /><figcaption>source- DeepSeek V3 paper [3]</figcaption></figure><p>So, that got me interested in their architecture. The first step in understanding it was the MLA architecture proposed in DeepSeek V2.</p><p>As DeepSeek-V2 paper mentions, KV-caching does indeed seem to be a bottleneck at inference time. The methodologies proposed so far to handle that, like Multi Query Attention(MQA, 2019[5]) and GQA( Group Query Attention, 2023 May[6]) came at the cost of a lowered performance. But not so in case of the Multi-head Latent Attention (MLA)[4] proposed in the DeepSeek V2 paper. It actually has a better performance than the vanilla Multi Headed Attention (MHA) from the original Transformers paper (Vaswani et al, 2017 [2]).</p><p>Llama 2 &amp; 3.1 use GQA while the Falcon models use a modified MQA. Lastly, another interesting paper on KV caching is the ICLR 2024 paper : “Model tells you what to discard: Adaptive KV cache compression for LLMs”[8].</p><p>Let’s cover some takeaways from each of these papers one by one. After doing a recap of the challenges of inference time, I will also try to explain the issues of KV Caching.</p><h3>Recap — Multi Headed Attention (2017, Vaswani) :</h3><p>As a recap for how self-attention works, we multiply the input embedding with <em>W(q) ,W(k), W(v)</em> matrices ( which we learn during the training) to get the Query vector Q ,Key vector K and Value vector respectively.</p><p>A pictorial representation of the above concepts :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*_HEtxUHUP6rP_YqMdwDNqw.png" /><figcaption>source- Bishop, chapter 12 [1]</figcaption></figure><p>The final output of the self-attention layer is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*vkDtQvjiLCItGkdWgby3nA.png" /><figcaption>Transformers paper (2017) [2]</figcaption></figure><p>In a transformer, we use h different such <em>W(k), W(q), W(v) </em>sets to get h different sets of self-attention heads. To quote the original transformer paper by Vaswani et al (2017) [2]:</p><blockquote>‘Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions.’</blockquote><p>so the key, query dimensions are <em>d/h</em> in case of h heads &amp; model dimension d, to keep the overall computation cost similar.</p><h3>Analyzing the challenges of MHA :</h3><p>The one -word answer is :<em> </em><strong><em>SLOOOW Inference</em></strong>. Let’s explore it in detail below.</p><p>So, one key point to note is that : <em>transformer is training is always done in parallel</em>, even for those with decoder architecture( which are autoregressive ). If you are not sure how that is done using a known ground truth, I would suggest that you check out the concept of “teacher forcing” or say, section 12.3.1 (“Decoder transformers” ) from the <a href="https://link.springer.com/book/10.1007/978-3-031-45468-4">Deep Learning book by Bishop.</a></p><h3><strong>Why LLM inference is serial :</strong></h3><p>in case of inference, in contrast to above training scenario, output tokens are always decoded <strong>serially</strong>. To explain the consequence of this, let me quote the 2019 MQA paper[5] : in case of (parallel) training process ( while using some masking) :</p><p>“First, we generate queries from n different positions in a sequence. These queries all interact with the same keys and values.”</p><p>However, that is not the case in case of decoding due to its auto regressive nature. The token of a self-attention layer at the current i-th position is affected by the output of the (i-1) th position ( i.e. by the key-value pairs produced by it ) and the other previous output tokens. But since the (i-1)th token was just freshly output, we need to add the new corresponding K-V pairs to memory at every timestamp. Thus, <em>no parallel computation is possible</em>. Hence the<em> slow inference</em>. More on this in next section.</p><p>(NOTE: <em>we do not load new W(k), W(v) matrices every time</em>, they are fixed for a given head &amp; layer combination.)</p><h4><strong>The challenges of KV Caching </strong>:</h4><p>By keeping all key-value pairs in memory — we avoid re-computation, but the price we pay is extra memory consumption. The challenges posed by this is explained is really well in the Adaptive KV caching paper [8].</p><p>So, we want to keep the key-value pair of all previous tokens in memory to avoid re-computation. But this KV cache scaled significantly with model size and generation length. <strong><em>But what if it exceeds GPU capacity ?</em></strong> We have no choice but to “offload” it to the CPU. Examples include “Deep Speed Inference” by Microsoft (2022 June) for multiple GPU and “FlexGen” (2023 March), for a single GPU.</p><blockquote>“While these methods help mitigate the pressure on the scarce GPU memory from using KV cache, offloading KV cache to CPU/NVMe can still add non-trivial overhead to generative inference performance due to the limited PCIe bandwidth between the GPU and CPU on many devices.”- Adaptive KV Caching paper [7]</blockquote><p>As a result, as they show in the “performance analysis” sections of the MQA paper, in case of inference, <strong>memory bandwidth</strong> becomes the major bottleneck for modern computing hardware.</p><h3><strong><em>What Multi Query Attention (2019) proposes</em> :</strong></h3><p>Inference decoding can become much <strong>faster</strong> if we have a single head for <em>key-value</em> while keeping things unchanged for query. <strong>Thus, if we had<em> (h *d *k), (h *d *v), (h *d *q) </em>for MHA → now the new dimensions are <em>(d *k), (d *v) </em>and (<em>h *d *q) </em></strong>where<em> h </em>is the number of heads.</p><p>Thus memory requirements are cut down by a factor of <em>h</em>. Experimental results show that the performance of MQA is only slightly worse than the baseline ( MHA), and is far better than cutting down the dimensions of either <em>h, d</em> or <em>k</em>.( Please check the below table 3)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*-jK-5efxwkSoTJIO6Geg-g.png" /><figcaption>source -MQA paper [5]: PPL stands for Perplexity — lower is better.</figcaption></figure><h3>2023 May — Grouped Query Attention</h3><p>This is a trade off between MHA &amp; MQA. MQA has 1 key-value pair for all the heads, and MHA has h pairs for all the heads — whereas GQA has g-pairs where g &lt;&lt;h. It is much faster than MHA &amp; performs much better than MQA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*jOHwgBFf29Ncnq1u49ouLQ.png" /><figcaption>source- Performance comparison : GQA paper [6]</figcaption></figure><h3>2023 — Modified MQA in Falcon models :</h3><p>Just a quick note on the timeline, Falcon 40B was released in May 2023, 180B in September 2023.</p><p>They tweaked MQA into what they called “<em>multi-group</em>” — an idea which is quite similar to GQA- the only difference being here the number of groups is same as the “tensor parallel rank” or the number of GPUs.</p><p>Their reasoning being, each GPU needs to have a separate copy of the key-value; they need to either share the gradients with each other or one GPU computes it and communicates with everyone else. They suggested, why not have a separate key-value pair for each GPU then ?</p><p>One important point mentioned in the Falcon paper is that, for model <em>training itself, FlashAttention is the key to speeding it up immensely</em>. But that might be the topic for another day !</p><h3>2024 May — DeepSeek V2 — Multi Head Latent Attention :</h3><p>Just recapping MHA from above, given an input vector x , we multiply it with <em>W(k), W(v), W(q)</em> to get the key, value and queries respectively. They each have a dimension of <em>d(h)</em> and there are total <em>n(h)</em> of them — n(h) being the number of heads.</p><p>Here, we project the input vector into a lower dimension vector, reload it and then project it into the actual, higher dimension key-query vector. In other words, given input vector x, we multiply it with W(DKV) , the down-projection matrix giving rise to c whose dimension <em>d(c)</em> is much, much lower than <em>d(h)*n(h)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNojJ6ubOXfn0sB6WNRmlw.jpeg" /><figcaption>source- DeepSeek V2 paper[4] : Note — h(t) here is the <strong>input</strong> vector</figcaption></figure><p>We can get the key and value by multiplying <em>c(t)</em> with two distinct up-projection matrices — thus, at inference time, we only need to load c(t). So the KV cache here is only <em>c(t) *l</em> where <em>l</em> is the number of layers.</p><p>Finally, we will close our discussion today with this awesome paper below :</p><h3>FastGen : Adaptive KV caching ( Published Oct 2023, ICLR 2024) :</h3><p>Their methodology achieved “∼40% memory reduction in Llama 1–65B, ∼30% in Llama 1–30B, ∼20% in Llama 1–13B and Llama 1–7B”[8]. Since the Llama2-chat version uses GQA, they used the original Llama-1(2023) with MHA version.</p><p>Here is the idea : Not all attention heads are same ! Here are the 5 types :</p><p>i) some only have a short, local context</p><p>ii) &amp; iii)some only pay attention to specific tokens/punctuation respectively</p><p>iv) some have attention maps that are column wise sparse — so we can safely discard the least frequently attended tokens</p><p>v) some pay attention broadly to all tokens</p><p>So why not discard the tokens a particular head is NOT interested in ? The quality loss for such adaptive compression is negligible ( able to recover 95%+ of attention scores)</p><p>Just a refresher, except special cases like MQA, in MHA, each head will have its own Wk, Wv matrices ( learnt through training) and consequently a different set of key-value vectors ( that needs to be cached for future token generation)</p><p>Based on the above structure analysis, here are the 5 different KV cache compression policies that they follow :</p><ol><li>Special Tokens only : keep only special tokens e.g. instruction token &lt;INST&gt; , start of the sentence token &lt;s&gt; in the KV cache. ( C special policy)</li><li>Punctuation tokens : keep only ”.”, ”:”, ”?” etc in the KV cache</li><li>Locality: once the context token &amp; current token exceeds the decided threshold — it is evicted from KV Cache</li><li>“Frequency ( Heavy Hitter)”: the cumulative attention sum is taken as frequency and the most frequent tokens are kept in memory.</li><li>Hybrid policy — different combinations of all 4 above. They found that out of these , special tokens &amp; punctuation token policies are especially important for attention map recovery, despite the fact that they are fewer in number.</li></ol><p>Now, the distribution of different Attention structures in different layers :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*RKLAWhwCsYi2YOBbgEJMsQ.png" /></figure><p>their observations :</p><ol><li>in the initial &amp; final layers, there are more attentions assigned to full KV cache</li><li>in the middle layers, the attention map focuses on special tokens (“the accumulated attention score on special tokens is higher than 0.95 for these attention heads.”[8])</li></ol><p>Thus, they suggest that we should first detect such underlying attention map structure before applying a separate compression policy to each attention head.</p><h3>References :</h3><ol><li>“<a href="https://link.springer.com/book/10.1007/978-3-031-45468-4">Deep Learning — Foundations and Concepts</a>”- Christopher M. Bishop, and Hugh Bishop. 1st edition, (2023)</li><li>Vaswani, A. (2017). Attention is all you need. <em>Advances in Neural Information Processing Systems</em>.</li><li>DeepSeek-V3 Technical Report , 2024 December — <a href="https://arxiv.org/abs/2412.19437">https://arxiv.org/abs/2412.19437</a></li><li>MULTI HEAD LATENT ATTENTION, Liu, A., Feng, B., Wang, B., Wang, B., Liu, B., Zhao, C., … &amp; Xu, Z. (2024). <strong>Deepseek-v2</strong>: A strong, economical, and efficient mixture-of-experts language model. <em>arXiv preprint arXiv:2405.04434</em>.</li><li>MULTI QUERY ATTENTION : Shazeer, N. (2019). Fast transformer decoding: One write-head is all you need. <em>arXiv preprint arXiv:1911.02150</em>.</li><li>Ainslie, J., Lee-Thorp, J., de Jong, M., Zemlyanskiy, Y., Lebrón, F., &amp; Sanghai, S. (2023). <strong>GQA</strong>: Training generalized multi-query transformer models from multi-head checkpoints. <em>arXiv preprint arXiv:2305.13245</em>.</li><li>Almazrouei, E., Alobeidli, H., Alshamsi, A., Cappelli, A., Cojocaru, R., Debbah, M., … &amp; Penedo, G. (2023). The <strong>falcon</strong> series of open language models. <em>arXiv preprint arXiv:2311.16867</em>.</li><li>Ge, S., Zhang, Y., Liu, L., Zhang, M., Han, J., &amp; Gao, J. (2023). Model tells you what to discard: Adaptive kv cache compression for llms. <em>arXiv preprint arXiv:2310.01801</em>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bb48c14e798" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/accelerating-llm-inference-with-efficient-self-attention-mqa-gqa-mla-deepseek-adaptive-kv-2bb48c14e798">Accelerating LLM Inference with efficient Self-Attention — MQA, GQA, MLA(DeepSeek), Adaptive KV…</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[Adagrad, Adadelta, RMSProp &Adam variants — Part 2 of Optimization algos for Deep Learning]]></title>
            <link>https://medium.com/@saurad44/adagrad-adadelta-rmsprop-adam-variants-part-2-of-optimization-algos-for-deep-learning-714400d1b44e?source=rss-82fbcbdab085------2</link>
            <guid isPermaLink="false">https://medium.com/p/714400d1b44e</guid>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[adaptive-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[adam]]></category>
            <dc:creator><![CDATA[Sauradeep Debnath]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 08:43:18 GMT</pubDate>
            <atom:updated>2025-07-15T19:43:28.511Z</atom:updated>
            <content:encoded><![CDATA[<h3>Adagrad, Adadelta, RMSProp &amp;Adam variants — Part 2 of Optimization algos for Deep Learning</h3><p><a href="https://medium.com/@saurad44/deep-intuition-about-gradient-descent-sgd-momentum-nesterov-part-1-of-optimization-algos-for-58d715036cb0">In my previous blog</a> , I covered the basic optimization algorithms- gradient descent &amp; its stochastic versions, momentum &amp; its Nesterov version. We covered their very intuitive interpretation by by <em>I.</em> <em>Sutskever &amp; Hinton. </em>I also cover some basic concepts from convex optimization.</p><p><a href="https://www.youtube.com/watch?v=-xpF7VyHeUA">In my YouTube video here</a>, I discuss about the complexity of the deep learning loss landscape and try to highlight the need for both momentum and adaptive learning rate.</p><p>Here we would cover a new set of optimization, called Adaptive learning algorithms. Here, in stead of having a global learning rate applied everywhere, we adapt it to different dimensions or different layers. For the first algo ADAGRAD (2011) , we first discuss the original paper and then give a more intuitive and simpler explanation from the Adadelta(2012) paper which tries to fix some of it faults. <strong>So don’t be discourged with the first paper’s complexity if you are overwhelmed, just skip ahead </strong>to the intuitive explanation section ( titled <em>“Adagrad(2011) : </em><strong><em>Interpretation</em></strong><em> </em><strong><em>2</em></strong><em> : Simple and Intuitive, </em><strong><em>from the Adadelta(2012) paper</em></strong><em> ”</em>).</p><p>We will first do an in-depth coverage of Adagrad(2011), Adadelta(2012), RProp(1993), RMSProp(2012), Adam (2015)— and then a very quick intro to its interesting variations like Nadam(2016), AMSGRAD(2018) , ADABOUND &amp; AMSBOUND(2019), RAdam( 2019/2020) and Adan(2023/2024), while doing a deep dive of the highly successful <strong>AdamW</strong>(2017/19) algorithm ( <strong>our Algo #10</strong>) while is highly popular in LLM training these days.</p><h3>Algo #1 : Adagrad, JMLR 2011 — uses adaptive learning rate :</h3><p><strong>Interpretation 1 : MATHEMATICAL/rigorous</strong> ( from the <strong>original</strong> paper)</p><p>First, they give the intuition that they want to increase the learning rates for the rare / infrequently occurring features as they have more predictive power, taking inspiration from older ideas like TF IDF.</p><p>Next, original Adagrad paper starts with the concept of <strong>Bregman divergence</strong> ; defined as the<strong> difference </strong>between<strong> </strong>the value of ψ at x and the first order Taylor expansion of ψ around y evaluated at point x :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*OPonSjyMASpSXyKCpm2--w.png" /><figcaption>Adagrad paper</figcaption></figure><p>Here ψ is called the <strong>proximal function</strong>. It could <em>Anything</em>, it just needs to be <em>strongly convex</em> and differentiable . What is strong convexity ? A function f is called m-strongly convex wrt a norm is f — (m/2) ||.||² is <a href="https://medium.com/@saurad44/deep-intuition-about-gradient-descent-sgd-momentum-nesterov-part-1-of-optimization-algos-for-58d715036cb0">convex</a> as well ( definition from Amir Beck, First Order Optimization). That is f remains convex even after deducting a quadratic term from it.</p><p>In other words, firstly, here is one way to define convexity &amp; strong convexity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*RgdDkDDih8D5xDxMcyGdWQ.png" /><figcaption>EE227C, Berkley</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*YzneHhVbAIhPSN4B-CnEug.png" /><figcaption>EE227C, Berkley</figcaption></figure><p>Please note that if ψ = 1/2 ||x||² , then Bregman divergence is reduced to squared Euclidean distance. If ψ is negative entropy, then Bregman divergence becomes KL divergence. In general Bregman divergence is not symmetric ( hence not a ‘metric’) ; and it is non -negative — zero only if x= y.</p><p>Anyway, so without going too deep into the rigorous mathematical treatment of that Adagrad paper ( <em>one of the toughest papers I have seen !!</em>), the main idea is there were a few existing online and stochastic algorithms which<em> use the proximal function ψ to control the gradient steps</em> of the algorithm ( with a fixed <em>ψ</em> ). What the current paper proposes is that we <em>adaptively modify ψ</em> by learning from the geometry of data.</p><p>Here they use the <strong>Mahalonabis norm </strong>as the proximal function. In general, squared Mahalonobis distance from x and μ is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*uY8uFqwm2fTm6dMPt-cQyA.png" /><figcaption>Bishop, Pattern Recognition</figcaption></figure><p>Where Σ can be any symmetric PSD matrix ( e.g. covariance matrix) . Note that this reduces to Euclidean distance if Σ is an identity matrix. Also, as we know, <em>norm</em> can be thought as distance of a point from origin. It is defined as wrt. to a given inner product &lt;.,.&gt; as ||v|| = √&lt;v , v&gt;.</p><p>Anyway, in case of Adagrad, proximal function is given by :</p><h4><em>ψ(x) = &lt;x, H x&gt;</em></h4><p>where H is a symmetic positive semi definite matrix constructed from the square root of <em>squared subgradients along a dimension i.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*hBmDzjcp4sUseOww-HKCtg.png" /><figcaption>Adagrad paper has 2 implementation. This above implementation is less computationally expensive than the “Full matrices” method where the definition of H(t) is slightly different</figcaption></figure><p>The above algo might look like a lot, but let me break it down for you.</p><p>(i) Each version of Adagrad ( be it the scalable “diagonal matrices” or the full matrices version) can be applied either for :</p><p>a. Nesterov’s Primal-dual method ( Eq 3 is its new, modified form) or</p><p>b. Proximal gradient ( composite mirror descent) method ( Eq 4) .</p><p>Thus you need to apply either Eq (3) or Eq (4), not both . These 2 algorithms are the topic for another day.</p><p>Also, please note, section 1.1 of the paper explains : those 2 original algorithms could already be written in the form of Eq (3)/Eq (4). The authors have just made <em>proximal function ψ adaptive, instead of being fixed.</em></p><p>(ii)In either case, we are trying to minimize a term which has 3 additive terms, one of them being either <em>ψ </em>or the Bregman divergence defined by it.</p><p>(iii)φ(x) is the regularization function</p><p>(iv) As we go through each iteration t, we keep appending the new ( sub) gradient to the vector g(1:t)</p><p>(v) s (i,t) captures the <em>square root of sum of squared (sub)gradients along i dimension</em> , from iteration 1 to t — thus capturing the second order information ( i.e. curvature)</p><h3>Adagrad(2011) : Interpretation 2 : Simple and Intuitive, from the Adadelta(2012) paper</h3><p>This was a very intuitive paper and very easy to read. Totally loved it :)</p><p>The author Matthew starts by highlighting the problem that finding just the right learning rate can be more of a art than science. If the LR is too high, the system will diverge, if it is too low, the convergence would take forever.</p><p>The paper mentions both Momentum and Adagrad among “Per Dimension First Order Methods”. E.g. in case of Momentum, it slows down the updates in dimensions where the sign of gradient changes a lot.</p><p>The paper gives a simplified formula for Adagrad( 2011) as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*mjmj6F8js68nhe6O_QQiEw.png" /><figcaption>Adadelta(2012) paper</figcaption></figure><p>The intuitive explanation : Dimensions with large gradients will have lower LR and vice versa. He notes that it is very optimal for very deep neural nets, as the magnitudes of gradients different layers are often different by “several orders of magnitude” — Thus Adagrad can help us get the right LR for each layer. Secondly, it has the natural effect of annealing or reducing the LR over iterations.</p><p>Among the downsides, this algo is still sensitive to the initial global LR. Secondly, if we look at the denominator, we can see there is a continuous accumulation of squared gradients — thus the training may become too slow eventually or even stop completely.</p><p>Adadelta, the author claims, was designed to specifically handle these two weaknesses.</p><h3>Algo #2 : Adadelta( 2012) — Google/NYU:</h3><p>Adadelta borrows the idea of having a denominator of root of squared gradients from ADAGRAD — but it does so only in a window w — to make sure the denominator does not go up to infinity, which can slow down and then even stop training prematurely.</p><p>But since storing last w gradients is inefficient, instead we implement it by exponentially decaying average :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*WJmAIjd5GMv1sbYT-AMAhA.png" /><figcaption>ρ here is the decay constant</figcaption></figure><p>Then we take a square root of this ( after adding a small constant Є ):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*GconyLt_93Ss5zmj77bnYA.png" /></figure><p>Now, the update could be learning rate/RMS[g(t)] — similar to the ADAGRAD formula.</p><p>But Adadelta goes a step further. They also wanted to remove the need for a need for manually selected global learning rate — hence they came up with this formula, assuming locally smooth curvature, and approximating the parameter update Δx(t) by an exponential averge till Δx(t-1) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*L7Gjn_3NNjRxAkWTBLfbRQ.png" /><figcaption>Weight update without a global learning rate. Note that the RMS formula includes small constant Є like before</figcaption></figure><p>The above fancy numerator comes from the logic that the units of Δx should match the units of x ( something that only the 2nd order Newtonian methods do ). But let’s leave those details for now.</p><p>The complete algorithm is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*8gl6XivBW7vJjskhYCxKmQ.png" /><figcaption>Adadelta paper, 2013</figcaption></figure><h3>Algo #3 : RPROP, 1993 — adapting the step size separately for each weight.</h3><p>Hinton’s famous algo RMSProp was designed as an improvement of the RProp ( resilient propagation ) algorithm from the <em>1993</em> paper by Riedmiller et al. Let’s understand the original algo first.</p><p>One interesting thing about RPROP:</p><blockquote>“we introduce for each weight its individual update-value Δ(ij), which solely determines the size of the weight-update.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*gZZsnbxldPBPodpnnXD8dQ.png" /><figcaption>RPROP paper, 1993</figcaption></figure><p>Intuitively, every time the partial derivative for that weight w(i,j) changes its sign, it indicates that the last update step was too big and we jumped over a local minimum, hence we reduce the learning rate by a factor of η- ( which is less than 1). If the derivate retains its sign from time (t-1) to t, we increase the update step to increase the speed of convergence.</p><h3>Algo #4 : RMSProp, introduced by Tieleman &amp; Hinton in their coursera classes in 2012 :</h3><p>Hinton explains in his class notes why RPROP — though working great for vanilla gradient descent — is not suitable for (Mini batch) Stochastic GD ( which is how every DL training is done in practice). Please recall my <a href="https://medium.com/@saurad44/deep-intuition-about-gradient-descent-sgd-momentum-nesterov-part-1-of-optimization-algos-for-58d715036cb0">previous artcle</a> that Stochastic GD only works as long as the <em>Expectation</em> (i.e. average) of the gradient update direction is the actual gradient ( which we can only obtain after iterating through the entire dataset).</p><p>He presents us with a <em>hypothetical case</em> where in a mini-batch we get a gradient of -0.1 9x, and +0.9X once , and the above requirement for SGD is violated :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJSPBUH3_3o8pguBlcy1PQ.png" /><figcaption>Hinton class notes.</figcaption></figure><p>Thus to combat these shortcomings, Tieleman &amp; Hinton came with RMSProp algo. Note, there are No published papers on RMSProp !</p><p>Whereas RPROP only used the sign of consecutive gradients, RMSProp uses the Exponential average of Squared gradients <em>( for each weight )</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suBCz9g9sZ4P5Xes3m5f6A.png" /><figcaption>Hinton class notes</figcaption></figure><h3>Algo #5 : Adam, ICLR 2015</h3><p>The ADAM paper mentions that just like ADAGRAD — this algo is good for sparse gradients. And just like RMSProp, it works great in online, non-stationary setting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*Q1j5gAeQUfbvnuUGxBLDuQ.png" /><figcaption>ADAM paper, ICLR 2015</figcaption></figure><p>Some interesting takeaways :</p><ol><li>m(t) and v(t) are here the estimates for the 1st moment ( mean) and 2nd moment ( uncentered variance)</li><li>But since they are initialized at 0, they would be “<em>biased towards 0</em>”, especially if the decay constant β1, β2 are close to 1, thus giving more importance to the previous estimate. That is why in the algo above , we call these “<em>biased</em>” 1st/2nd moment estimates.</li><li>invariance to gradient size : Scaling the gradients by c will scale the m(t) by c, and v(t) by c² , hence they cancel out in the effective step size Δ(t) ∝ c.m(t)/√( c² v(t)) = m(t)/v(t)</li><li>Signal-to-Noise Ratio ( SNR) — the ratio of m(t)/√v(t) can loosely be thought as signal to noise ratio. When there is low SNR, the effective step size Δ(t) becomes low/nearly zero ( e.g. near the optimum)- thus leading to <em>automatic annealing</em> . The authors explain, this makes sense because :</li></ol><blockquote>“a smaller SNR means that there is greater uncertainty about whether the direction of bmt corresponds to the direction of the true gradient ”</blockquote><p>5. Bias corrected estimates — INTUITION : if β is close to 1, then 1 — β^t is close to 0 if t is small, close to 1 if t is high. Thus if we divide the biased estimates by ( 1 — β^t) term, the estimates are multiplied by a term &gt;&gt;1 initially, and in later iterations, the effect becomes negligible. This really helps with the initialization zero bias of the estimates. NOTE — this was not present in previous algorithms like ADAGRAD or RMSProp.</p><p>DERIVATION : But how do they come up with the formula ?</p><p>Firstly, we have the original formula of v(t) :</p><p>v(t) = β2 * v(t-1) + (1- β2)* g² (t)</p><p>By substituting the values of v(t-1) to v(1) recursively, this can be re-written as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*kGQMdkvJD0D0UkZqcWNqjg.png" /><figcaption>ADAM paper</figcaption></figure><p>Now if we take expectation both side and then taking the constants out of the expectation, we get :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*WQQzI8AIpuWlx5JxkXUxOw.png" /><figcaption>ADAM paper</figcaption></figure><p>Which shows the relation of the expected value of the exponential moving average with the true 2nd moment E[g² (t)]. The formula of bias correction was derived from here, by dividing both sides by ( 1 — <strong>β2^t )</strong></p><h4>Experimental results :</h4><p>The authors of ADAM found that although both ADAM and ADAGRAD made great progress in the initilial phases of training ( in terms of lowering the training cost ) , ADAGRAD slows down later on, thus both ADAM &amp; SGD-Nesterov converge considerably faster than ADAGRAD :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*00AzKpoC7CYQsyZhcOUbVA.png" /><figcaption>ADAM paper</figcaption></figure><h3>ADAM Variants :</h3><p>ADAM is still one of the best performing algorithms. But here are a few new variants, out of them AdamW(2019) is the one which is most popularly used.</p><h4>Algo #6 : Nadam, ICLR 2016</h4><p>“Incorporating Nesterov Momentum into Adam” proposes <strong>Nadam</strong> — and it finds that it did drastically better than Adam in their experiments. They also argued that this is not surprising given that vanilla Nesterov ( NAG) performs so much better than classical Momentum.</p><h4><strong>Algo #7 : AMSGRAD , ICLR 2018</strong></h4><p>“On the Convergence of Adam and Beyond” — proposes a version of Adam called <strong>AMSGRAD</strong>: They mention that empirically it has been shown that algorithms that use the exponential moving average of squared gradients ( like Adagard, RMSProp, Adam, Nadam) can often fail to converge at an optimal point. They also mention for a guarantee of convergence, we need a “long term memory of past gradients”.</p><p>They achieve this by doing this small tweaking :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*eIA9gtsqJq5cQCE6JvWfDQ.png" /><figcaption>AMSGRAD</figcaption></figure><p>So, instead of normalizing m(t) by dividing it by v(t) like ADAM, here the numerator is a max between current v(t) and its highest value so far, thus ensuring a <em>non -decreasing step size</em> — which they point out is the major mistake that Adam and RMSProp does. ( ADAGRAD, on the other hand, just reduces step size way too quickly, as discussed earlier)</p><h4><strong>Algo #8 &amp; #9 : ADABOUND and AMSBOUND , ICLR 2019</strong></h4><p>“Adaptive Gradient Methods with Dynamic Bound of Learning Rate” proposes 2 new variants of ADAM and AMSGRAD, called ADABOUND and AMSBOUND respectively to improve the <em>generalizability</em> of Adaptive methods on unseen data ( as compared to SGD( + momentum)). They mention even AMSGRAD doesn’t do that well in terms of generalizability ; it wasn’t good enough as it ignored learning rates that are too small.</p><p>These algorithms start as Adaptive methods (to enjoy a rapid initial training), but gradually converge to an SGD (to achieve a good generalizability). They do so by <em>clipping</em> the learning rate between a upper and lower bound — which are initially 0 and ∞ — and are gradually <em>restricted</em> till they converge to a single point.</p><h3>Algo #10, AdamW, ICLR 2019 — Popular for LLM training:</h3><p>This is one is highly popular these days, <strong><em>used in a lot of popular LLMs</em></strong> like Llama 2/3.1 ( while GPT3, BERT uses Adam).</p><p>AdamW paper starts by pointing out that the state-of-the-art at image classification dataset is always achieved by SGD with momentum, and not with Adaptive methods like Adam or AMSGRAD. This is because Adaptive algorithms are not as good in generalizing, as many other papers have concluded before.</p><p>The paper mentions that one reason for this poor generalization by Adam is that weight decay and L2 regularization are not equivalent for adaptive gradient methods, unlike the case of SGD. <em>L2 regularization is not as effective for Adam</em> — but that is what most common deep learning libraries implement.</p><p>They mention that Adam can achieve over 15% improvement in test errors from a decoupled weight decay in image recognition tasks like CIFAR-10 and ImageNet32x32. But what is this decoupled weight decay ?</p><p>Firstly, this is the weight decay formula given by Hanson &amp; Pratt in 1988 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*_y-va_obI-96VGMbSBymzw.png" /><figcaption>AdamW paper</figcaption></figure><p>And this is the equivalent L2 regularization for standard SGD, both push the weights closer to 0 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*eCuA6bDh6sNyX5jUGCImbw.png" /><figcaption>AdamW paper</figcaption></figure><p>They are equivalent for SGD, but still the regularizer λ’ is tightly coupled with the learning rate α. Now for the Adaptive gradient methods, when we use the L2 regularization, both loss function f and the gradients get scaled. Thus regularization term is in both the numerator and denominator ( and kinda cancels out). That’s why, the authors found that :</p><blockquote>“when combined with adaptive gradients, L2 regularization leads to weights with large historic parameter and/or gradient amplitudes being regularized less than they would be when using weight decay.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KY7Osf51KVkclA18ksR9nQ.png" /><figcaption>Adam+L2 vs AdamW comparison : from AdamW paper</figcaption></figure><p>As an interesting side fact : Even though Adam has a built-in annealer, they found that it does benefit from a scheduled learning rate multiplier like cosine annealer ( though not as drastically as SGD for obvious reasons)</p><h4><strong>Algo #10 , Radam, ICLR 2020</strong></h4><p>“On the Variance of the Adaptive Learning Rate and Beyond” proposes a new version of Adam called <strong>Radam</strong>( Rectified Adam) <strong>. </strong>They mention this very interesting fact that both the original Transformer paper &amp; BERT paper mentioned — unless they did an “warm up” with small learning rate at the start, they tend to get stuck in a “bad/suspicious local minima”. This paper suggests a tweak in Adam algorithm to handle this problem during the initial steps, by introducing a variance rectification term.</p><h4>Algo #11 : Adan ,IEEE 2024 :</h4><p>“<strong>Adan</strong>: Adaptive Nesterov Momentum Algorithm for Faster Optimizing Deep Models” proposes an improvement over <strong>Nadam.</strong></p><p>That’s it for today !</p><h3>References :</h3><ol><li>class Notes : <a href="https://people.iith.ac.in/saketha/teaching/cs5660.html">Convex Optimization 2 : Algorithms</a>, by Prof Saketha Nath, IIT Hyderabad/IIT Bombay</li><li>class Notes: Neural Networks for Machine Learning- Geoffrey <strong>Hinton</strong> et al</li><li><strong>JMLR 2011 </strong>: Duchi, J., Hazan, E., &amp; Singer, Y. (2011). Adaptive subgradient methods for online learning and stochastic optimization. <em>Journal of machine learning research</em>, <em>12</em>(7).</li><li>Zeiler, M. D. (2012). ADADELTA: an adaptive learning rate method. <em>arXiv preprint arXiv:1212.5701</em>.</li><li>M. Riedmiller and H. Braun, “A direct adaptive method for faster backpropagation learning: the RPROP algorithm,” <em>IEEE International Conference on Neural Networks</em>, San Francisco, CA, USA, <strong>1993</strong>, pp. 586–591 vol.1, doi: 10.1109/ICNN.1993.298623.</li><li>Kingma, D. P. and Ba, J. Adam: a method for stochastic optimization. In <strong>ICLR, 2015</strong>.</li><li><strong>ICML 2021</strong> : Schmidt, R. M., Schneider, F., &amp; Hennig, P. (2021, July). Descending through a crowded valley-benchmarking deep learning optimizers. In <em>International Conference on Machine Learning</em> (pp. 9367–9376). PMLR.</li><li>Papers on Nadam(2016), AMSGRAD(2018) , ADABOUND &amp; AMSBOUND(2019) , RAdam( 2019/2020) and Adan(2023/2024) — Quoted above, towards the end of the article</li><li><strong>AdamW : ICLR 2019</strong> : Loshchilov, I. (2017). Decoupled weight decay regularization. <em>arXiv preprint arXiv:1711.05101</em>.</li><li>EE227C, Berkley, <a href="https://ee227c.github.io/notes/ee227c-lecture03.pdf">https://ee227c.github.io/notes/ee227c-lecture03.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=714400d1b44e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Intuition about Gradient Descent, SGD, Momentum, Nesterov— Part 1 of Optimization algos for…]]></title>
            <link>https://blog.gopenai.com/deep-intuition-about-gradient-descent-sgd-momentum-nesterov-part-1-of-optimization-algos-for-58d715036cb0?source=rss-82fbcbdab085------2</link>
            <guid isPermaLink="false">https://medium.com/p/58d715036cb0</guid>
            <category><![CDATA[momentum]]></category>
            <category><![CDATA[stochastic-gradient]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[optimization-algorithms]]></category>
            <dc:creator><![CDATA[Sauradeep Debnath]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 10:28:28 GMT</pubDate>
            <atom:updated>2025-08-01T18:00:35.078Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Intuition about Gradient Descent, SGD, Momentum, Nesterov— Part 1 of Optimization algos for Deep Learning</h3><ol><li><a href="#706b">Convex Optimizaion &amp; the Mathematical interpretation for basic Optimization algorithms</a></li></ol><p>2. <a href="#9ea4">Understanding the Basic algos : Intuitive Interpretations</a></p><p>Hi guys, Sauradeep here, back with another exploration of AI/ML topics and related research papers, this time on a very fundamental topic — the basic optimization algorithms used in Deep Learning. After giving a brief background of how these algorithms classically were originally formulated for different <em>convex optimization</em> scenarios, we will start from analyzing &amp; giving intuitions for Gradient Descent, then move to its stochastic variation, before jumping into some of the accelerated variations. We also do a deep dive of some of the amazing intuitions from the ICML 2013 paper by <em>I.</em> <em>Sutskever (</em>Co-Founder and Chief Scientist of OpenAI<em>)&amp; Hinton ( Nobel Prize in Physics, 2024).</em></p><p>Check out my <a href="https://www.youtube.com/watch?v=-xpF7VyHeUA">YouTube video</a> for a detailed intuition on the topic, specifically on the complexity of deep learning loss landscape.</p><h3>Convex Optimizaion &amp; the Mathematical interpretation for basic Optimization algorithms :</h3><p>So, firstly, Stochastic Gradient Descent(<strong>SGD</strong>) was introduced by Herbert Robbins and Sutton Monro in <strong>1951</strong> in a paper called “A stochastic approximation method”.</p><p>The <strong>Momentum</strong> paper “Some methods of speeding up the convergence of iteration methods ”(Polyak, <strong>1964</strong>) is way too rigorous for my current grasp of abstract mathematics— talking about “spectral theory in Banach space” and “commutative normalized rings”; hence I left it for a later date. The only take way I had was from the introductory paragraph where they mention : they have proved in this paper that multi step methods — where we consider past k iterations, converge much faster than 1-step methods.</p><p>We will discuss the simplified and <em>intuitive</em> re-interpreation of Momentum ( and the following algo) in 2nd half of the article, following the papers and class notes of <em>Hinton</em>.</p><p>Before going to the next algo, let us understand what is <strong>convex optimization</strong>, since <em>all these algos were originally derived for convex optimization</em>, later we just found experimentally that they work great for deep learning.</p><p>A set C is called a <strong>convex set</strong> if any line segment between two points x and y also lies in C i.e. for 0&lt;θ&lt;1 :</p><h4>θx + (1-θ)y ∈ C , ……….∀ x, y∈ C</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*eb2hi1DZu5dW0N9jlFoh_w.png" /><figcaption>Convex vs Non convex Sets, Boyd and Vandenberghe</figcaption></figure><p>A function f is called <strong>convex function</strong> if the domain of f is a convex set &amp; the any line segment connecting (x, f(x)) and (y,f(y)) lies above the function f at any point i.e. mathematically :</p><h4>f( θx + (1-θ)y) ≤ θ f(x) + (1-θ) f(y) …… ∀x, y ∈ domain(f)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*iZAT2vC4AwaGJnCyxOlPaQ.png" /><figcaption>Convex function, Boyd and Vandenberghe</figcaption></figure><p>Now, that we understand these two concepts, a <strong>convex optimization problem</strong> is really simple concept , it is of the form :</p><p>Minimize the objective function f(x)</p><p>subject to inequality constraints gₖ(x) ≤ 0 , k = 1… m</p><p>and equality constraints aₖT x = bₖ , k = 1… n ( T here stands for transpose)</p><p>where both f(x) and gₖ(x) are convex functions, and the equality constraints aₖT x — bₖ are <em>affine</em> functions ( linear, but need not pass through origin, of the form Ax+b)</p><p><strong><em>Now off to our next algorithm.</em></strong></p><p>In <strong>1983</strong>, <strong>Nesterov</strong> came out with Nesterov Accelerated Gradient Descent ( <strong>NAG</strong>) algo in “A method for solving the convex programming problem with convergence rate O(1/k²)”.</p><p>To understand the context, here is the summary of convergence guarantees for different scenarios :</p><p><strong>CASE 1:</strong> for a general <strong>convex optimization</strong> problem, we realized pretty early on that gradient ( sub-gradient) descent was the optimal algo, with convergence rate of O(1/√k). That is, after k iterations of the algo , we will get at least one value of x(i) that gets us f(x(i)) close enough to the optimal value f* such that we get an error of O( 1√k).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*eW2M5UU4xbjrfZnaGvxZSA.png" /><figcaption>Prof Saketha Class Notes</figcaption></figure><p><strong>CASE 2:</strong> <strong>Smooth- Convex problems:</strong></p><p>First, let us understand smoothness.</p><p>A function is called ‘L-smooth’ if || ∇f(x) — ∇f(y) || &lt; L ||f(x) — f(y)||, where L is a constant. Geometrically, it means no sharp corners ( it is a stronger condition that differentiability).</p><p>Turns out, for <em>Smooth-Convex problems</em> gradient descent was giving a Convergence rate of O(1/k).</p><p>But then Nesterov came up with a new algo NAG, using the properties of both smoothness and convexity, which gave an <em>improved convergence of convergence rate of O(1/k²)</em>. His algo can be interpreted as a linear combination of one smooth update step and convex update step. ( for more details check out the 2016 paper — “Linear Coupling: An Ultimate Unification of Gradient and Mirror Descent” by Zeyuan Allen-Zhu et al)</p><p>We will see a new re-interpretation of this algo by Ilya Sutskever &amp; Hinton below shortly.</p><h3>Understanding the Basic algos : Intuitive Interpretations :</h3><p>Now let’s first try to understand these basic algorithms, while trying to minimize the maths and trying to avoid too many definitions from convex optimization.</p><h3><strong>Algo #0 : Gradient Descent :</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*suJ0Vx8mH7Wgk0RbLqE6RQ.png" /><figcaption>Book : Shai Shalev Shwartz</figcaption></figure><p><em>Shai Shalev-Shwartz</em>, in section 14.1 of his <a href="https://www.amazon.in/Understanding-Machine-Learning-Theory-Algorithms-ebook/dp/B00J8LQU8I">book on ML</a> gives 2 different interpretations of gradient descent. Firstly, the derivative of the objective f “points in the direction of the greatest rate of increase of f around w(t)”. That’s why one interpretation of gradient descent is <em>being greedy</em> wrt. that (by going opposite the instantaneous direction of steepest ascent).</p><p>The second interpretation is that of a locally linearly approximating f(w) and then moving to a minimization of that. I will likely to directly quote the book, since he explains it so clearly :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*Yjnvve7dotnriA61P2Mxrg.png" /><figcaption>Shai Shalev Shwartz</figcaption></figure><p>This concept of Gradient Descent can be extended to non -differentiable functions by using the idea of subgradients :</p><p>a subgradient v of a function f at a point w is any vector that satisfies the below “subgradient inequality” :</p><h4>f(u) ≥ f(w) + &lt;u-w, v&gt;</h4><p>where the inner product / dot product &lt;u-w, v&gt; gives the supporting hyperplane at point u ( a tangent line through w, but passing below it) . Even if you don’t get the math, the below illustration should give you some intuition. Note that if the function f is differentiable at point w, the only subgradient it has is the gradient itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*ccu8RzwVZtOWIaGoItzvWw.png" /><figcaption>Shai Shalev Shwartz : illustration of sub gradients</figcaption></figure><p>The collection of all such subgradients of f at point w is called the sub-differential set δf(w).</p><h3><strong>Algo #1 : Stochastic Gradient Descent (SGD, 1951):</strong></h3><p>In SGD, we do not require the update direction to be based exactly on gradient. We can let it be any random vector as long as its expectation is the gradient ( or, to generalize to non-differential case, one of the subgradients i.e. belongs to the subdifferential set δf(w) )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*bqkKGUVNPoyWVzk6Ua4lig.png" /><figcaption>SGD : Shai Shalev Shwartz</figcaption></figure><p>We implement this by sampling a data point i.i.d. from the dataset D and by taking the gradient ( subgradient ) as the unbiased estimate of the actual gradient ( subgradient). In practice, however, in deep learning , what we do is half way between vanilla and stochastic GD. We neither do loop through the entire dataset ( entire batch) before updating the weights, nor do we update them after every training data point. Rather we do so after every mini batch ( say of 32, 64, 128 etc. ) , thus doing a <em>Mini Batch SGD</em>.</p><p>As Geoffrey Hinton covers in his class notes, now each weight update takes far less computation ( compared to vanilla GD). And we can calculate the gradients for the entire mini batch simultaneously, thanks to GPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgNX14G2s6Uv8577UMCg_g.png" /><figcaption>Geoffrey Hinton class notes</figcaption></figure><h3>Algo #2 : Momentum (1964) :</h3><p>Here is the very awesome intuition from Geoffrey Hinton’s notes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDfE42XqrQX7_Z0s6UYikQ.png" /><figcaption>Hinton, class notes</figcaption></figure><p>So how do we implement it ? instead of updating weights by adding (learning rate) x (negative gradient), we add a linear combination of the (older “velocity”) and (learning rate)x(current gradient ) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*n25b2xcZUR92TYamkkgmqA.png" /><figcaption>Paper 1 from references</figcaption></figure><h3><strong>Algo #3 : Nesterov Momentum ( NAG, 1983)</strong> :</h3><p>We have already discussed the convex optimization interpretation of NAG. <em>Ilya Sutskever &amp; Hinton</em> re-derived NAG as a form of Momentum in their <strong>ICML 2013</strong> paper ( “ <strong>On the importance of initialization and momentum in deep learning.”</strong>), re writing it in the below form :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*egr7tYPLdD_T8ZFAgHZIrg.png" /><figcaption><em>Sutskever &amp; Hinton, ICML 2013</em></figcaption></figure><p>The intuition is as follows : both classical momentum ( by Polyak, which the current authors call abbreviate as “CM”) and NAG use a form of gradient to update the new velocity. But whereas, CM uses the current gradient, NAG uses the gradient at point θ(t) + μv (t)( i.e. what if we took a step size of μ along the v(t) and then checked the gradient).</p><p>They noted that if v(t) is indeed a poor update, ∇f(θ(t) + μv (t)) will provide a stronger and more timely corrections than ∇f(θ(t))- thus<em> decelerating more effectively along directions of high curvature</em> ( i.e. frequent change of direction) and avoid too much oscillations. Thus it is a more stable algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*FBH3mJ-G7y08ERlpsriNrA.png" /><figcaption><em>Sutskever &amp; Hinton, ICML 2013</em></figcaption></figure><p>Secondly, they note that for deep learning, the <em>transient state of convergence is more important than the final convergence </em>( takes a bigger chunk of training time) — unlike the case of convex objective. This is something the earlier research had ignored. Theoretically, CM &amp; NAG will provide better performance in the transient phase, but will perform equally well in the final phase.</p><p>They prove this experimentally by training auto encoders with mini batch 200. They find NAG could show performance similar to 2nd order, Truncated Newton methods like Hessian Free Optimization (HF, 2010) — which they show in the paper, performs much better than plain SGD ( Momentum fared better than SGD).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*IPGs6acnMbV4lIc9pxt25w.png" /><figcaption><em>Ilya Sutskever &amp; Hinton( ICML 2013)</em></figcaption></figure><p>That’s it for today. In the next article, we will cover Adam &amp; other Adaptive algorithms, which are most prominently used today in deep learning.</p><p>Here is the link for Part 2 : <a href="https://medium.com/@saurad44/adagrad-adadelta-rmsprop-adam-variants-part-2-of-optimization-algos-for-deep-learning-714400d1b44e">https://medium.com/@saurad44/adagrad-adadelta-rmsprop-adam-variants-part-2-of-optimization-algos-for-deep-learning-714400d1b44e</a></p><h3>References :</h3><ol><li>class Notes : <a href="https://people.iith.ac.in/saketha/teaching/cs5660.html">Convex Optimization 2 : Algorithms</a>, by Prof Saketha Nath, IIT Hyderabad/IIT Bombay</li><li><strong>Book</strong> : <a href="https://web.stanford.edu/~boyd/cvxbook/">Convex Optimization — Boyd and Vandenberghe</a></li><li><strong>Book</strong> : Shai Shalev-Shwartz and Shai Ben-David.<a href="https://www.amazon.in/Understanding-Machine-Learning-Theory-Algorithms-ebook/dp/B00J8LQU8I"> “Understanding Machine Learning : From Theory to Algorithms”</a>, Cambridge University Press, New York, NY</li><li>class Notes: Neural Networks for Machine Learning- Geoffrey <strong>Hinton</strong> et al</li><li>PAPER 1 : ICML 2013 : Sutskever, I., Martens, J., Dahl, G., &amp; <strong>Hinton</strong>, G. (2013, May). On the importance of initialization and momentum in deep learning. In <em>International conference on machine learning</em> (pp. 1139–1147). PMLR.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58d715036cb0" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/deep-intuition-about-gradient-descent-sgd-momentum-nesterov-part-1-of-optimization-algos-for-58d715036cb0">Deep Intuition about Gradient Descent, SGD, Momentum, Nesterov— Part 1 of Optimization algos for…</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[Policy Based Deep RL — part 2 of Reinforcement Learning Series]]></title>
            <link>https://blog.gopenai.com/policy-based-deep-rl-part-2-of-reinforcement-learning-series-cdca33709ea2?source=rss-82fbcbdab085------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdca33709ea2</guid>
            <category><![CDATA[control]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[deep-rl]]></category>
            <category><![CDATA[markov-decision-process]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Sauradeep Debnath]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 20:04:24 GMT</pubDate>
            <atom:updated>2025-02-23T12:46:10.228Z</atom:updated>
            <content:encoded><![CDATA[<h3>Policy Based Deep RL — part 2 of Reinforcement Learning Series</h3><p>In my <a href="https://medium.com/@saurad44/reinforcement-learning-part-1-model-based-model-free-function-approximation-4501e317e9d6">previous blog</a>, I covered the basics of RL, covering the scenarios of Model based (Planning), Model Free ( Learning), Function Approximation ( e.g. deep-Q-network/ DQN).</p><p>Here are the content of this blog :</p><ol><li>Value Based RL vs Policy Based RL</li><li><a href="#2e3e">General Implementation of Policy based RL</a></li><li><a href="#c82b">Algorithm 1 : REINFORCE</a></li><li><a href="#a8d5">Algorithm 2 : Policy Gradient</a></li><li><a href="#aa67">Algorithm 3 : Natural Policy Gradient(2001)</a></li><li><a href="#9197">Algorithm 4 : TRPO(2015)</a></li><li><a href="#c363">Algorithm 5: PPO (2017)</a>— which is very popularly used for RLHF ( Reinforcement Learning from Human Feedback) for LLM these days.</li></ol><h3>Value based RL vs Policy Based RL :</h3><p>In DQN , we have been approximating the value function Vπ​ or action value function Qπ with parameters φ of a neural network. And then we were deriving the policy from the value function e.g. <a href="https://medium.com/@saurad44/reinforcement-learning-part-1-model-based-model-free-function-approximation-4501e317e9d6">by ε-greedy strategy</a>.</p><p>But what if we parameterized the policy π directly ? The resulting<strong> <em>Policy based RL algorithms</em> </strong>will have better convergence; it is relatively easier in high-dimensional or continuous action space as compared to value based methods. It can even learn <em>stochastic policies</em> — which value based RL cannot. On the flip side, it tends to converge at a local, rather than global optima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7UyjwJxeRLE5jjOQulTcQ.png" /><figcaption>David Silver, “PG”</figcaption></figure><h3><strong>General Implementation of Policy based RL :</strong></h3><p>How is it actually implemented here ?</p><ol><li>For discrete action space, it could output a vector of probabilities</li><li>For continuous action space, it could output the parameters of the distribution ( e.g. μ, σ for normal distribution )</li></ol><p>We want to <strong>find the optimal stochastic policy</strong> π* (θ) which maximizes the loss function J(θ) = Vπ(θ). Hence we want to<strong> ascend the loss landscape</strong> by changing θ by Δ θ =α ∇ J(θ) (where ∇ → gradient, α — step size parameter).</p><p>After doing some simple algebra and replacing the expectation with average ( to get a model free /sample based estimate), we get :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*xRC02qwrFLUDFk6Dl4PnqQ.png" /><figcaption>IIT Hyd Classnotes, “Policy Gradients ”. Here 𝜏 denotes the trajectory i.e. the s0, a0, s1, a1,… etc. sampled from policy π(θ)</figcaption></figure><h3>Algorithm 1 : REINFORCE :</h3><p>Here is our first Policy based algo <strong>REINFORCE</strong>(1992) — a model free algo :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*WZ02FYNPnV7VeADwjBdCdA.png" /><figcaption>IIT H class notes</figcaption></figure><p><em>Issues with above algorithm </em>: this gradient estimate is high variance as we are sampling stochastic paths ; hence the convergence is slow. In their <em>NIPS 1999 paper “</em> Policy Gradient Methods for Reinforcement Learning with Function Approximation”<em>,</em> <em>Richard Sutton</em> et al mention that this <em>slowness</em> is the reason REINFORCE never received much attention.</p><p><em>Solution</em> : We need to apply some Variance reduction methodology. We apply 2 such variance reduction techniques to arrive at the vanilla Policy Gradient algorithm (<strong>Algorithm #2</strong>)below.</p><h3>Algorithm 2 : Policy Gradient :</h3><ol><li>we discard some terms from Gt considering the principle of causality ( i.e. policies at current time t cannot effect the rewards we get in the past i.e. before time t ). If you check the formula for Gt below, the summation starts at time t.</li><li>We subtract a baseline b from the rewards to get zero mean — without impacting the gradient directions. There are multiple options for it — but a good baseline is a constant baseline with the value of expected gain.</li></ol><p>So, here are the general forms of Policy Gradient algorithm and the different options of baseline :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIbtmayN9A2_LQeGoGnanw.png" /><figcaption>GAE paper(2015)</figcaption></figure><p>The GAE paper justifies this way why the Advantage A(s,a) is the best option :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIV2BQmfSQeNtxWkDEi43w.png" /><figcaption>GAE paper[13]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYdoFg2-M85kW6i7t_aDbw.png" /><figcaption>IITH Classnotes</figcaption></figure><p>Which leads to the above form of policy gradient formulation.</p><p><strong><em>LIMITATIONS</em></strong> : But this Policy Gradient algorithm has a bunch of limitations as well.</p><ol><li><strong>Sample inefficiency</strong> : this algo is on-policy i.e. only uses samples from the current policy. It also doesn’t recycle old data. We can use <em>importance sampling</em>, but it might lead to problems of vanishing or exploding gradients.</li></ol><p>Understanding <em>Importance Sampling </em>: Suppose we want to estimate E[f(x)] where x ~ p(x). Now to estimate the expectation from sampling ( e.g. Monte Carlo) , we need to sample from p(x). But what if p(x) is hard to sample from ? Can we use samples from a different distribution q(x) ? Turns out, the answer is : yes, by using a sampling ratio p(x)/q(x)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*Gsk4EZ0woMOSyQuftN-8lw.png" /><figcaption>Sergey Levine, Importance sampling</figcaption></figure><p>But applying IS to PG can lead to vanishing or exploding weights :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2Y5R1YsBCg7rV5hWDSsbQ.png" /><figcaption>IITH classnotes, PG with Importance Sampling (IS)</figcaption></figure><p>2. <strong>Limitation #2</strong> : <strong>Updates in the parameter space</strong> : As we can see in the step 6 of the vanilla Policy Gradient algorithm above, we are taking a step Δθ =α ∇ J(θ) in the parameter space ( i.e. θ).</p><p>But since distance in parameter space ≠ distance in policy space. So, it is difficult to get the step size right. If the step size is too big, then we might overshoot the optima by a large margin, thus leading to a performance collapse ; and if it is too small, then the progress will be slow.</p><p>The efforts to solve these limitations take us to natural policy gradient (2001), TRPO (2015), PPO(2017). Before diving deeper into them, here are some salient features about each of them</p><p>NPG — Takes account of step sizes in the policy space, using KL Divergence/ Fisher information matrix.</p><p>TRPO= NPG +Line Search +Monotonic Improvement Theorem</p><p>Both NPG and TRPO use 2nd order information ( Fisher matrix). PPO does not and thus simplifies the computation.</p><p>Now, let’s explore them in depth one after another :</p><h3>Algorithm #3 : Natural Policy Gradient (2001) :</h3><p>The NPG paper(2001) quotes the 1998 paper by S. Amari ( a paper surprisingly hard to find on the internet :) ) : “As suggested by Amari [1], it is better to define a <em>metric based not on the choice of coordinates but rather on the manifold (i.e. the surface)</em> that these coordinates parameterize. This metric defines the natural gradient” , as opposed to doing a gradient descent in the parameter space.</p><p>Further they mention :</p><blockquote>“As shown by Amari (see [1]), the Fisher information matrix, up to a scale, is an <strong><em>invariant</em></strong><em> metric on the space of the parameters of probability distributions</em>. It is invariant in the sense that it defines the same distance between two points regardless of the choice of coordinates (i.e. the parameterization) used”</blockquote><p>Thus since Fisher information matrix F(θ) denotes the distance on the probability manifold, the steepest descent in the probability manifold of policy is given by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*YpRi1_dVmYCy9F2Y6wnNxg.png" /><figcaption>NPG paper, 1999</figcaption></figure><p>We can show mathematically, F is nothing but the Hessian of KL divergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-9vxoEEgscfDVaTNfMjEhQ.png" /><figcaption>CMU RL notes</figcaption></figure><p>This NPG algorithm shows a drastic performance improvement ( as opposed to standard PG) in simple MDPs as well as the more challenging, (and high -dimensional) game of Tetris.</p><h3><strong>Algorithm #4 : Trust Region Policy Optimization (2015):</strong></h3><p>The TRPO paper mentions their main contribution is theoretically proving that minimizing a certain surrogate objective function can lead to guaranteed policy improvement with <em>non-trivial ( large enough) step sizes</em>. Then they suggest a series of approximations for the practical implementation of the algorithm. This algorithm is scalable and hence can handle policies of tens of thousands of parameter ( it was very challenging at that time) and thus can learn complex policies like robotic swimming, hopping, walking in a simulation (first time ever, without a non-engineered general-purpose policy )and playing Atari games from raw images.</p><p>They mention the optimization problem they are trying to solve is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*iE-qh5jfDat-Ha2uuA5XZA.png" /><figcaption>TRPO paper</figcaption></figure><p>where this heuristic approximation to KL divergence is easier to solve ( as the original KL divergence is too computationally expensive due to the sheer huge number of constraints) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*PWayV9_HGsI1ao6CrvUOmA.png" /><figcaption>TRPO paper</figcaption></figure><p>and Lθ , as defined in Eq(3) and section 4 of the paper, is the local approximation to the discounted expected reward for policy πθ.</p><p>Under section 7, “Connections to previous work”, they mention something very interesting. If we take a linear Taylor series approximation to L, and a quadratic approximation to the heuristic KL divergence, we arrive at nothing but Natural Policy Gradient (Kakade, 2002).</p><p>Now, the CMU RL Notes say, TRPO is nothing but NPG + Line Search + Monotonic improvement Theorem. We will leave out the last point, due to its theoretical nature and just try to understand Line Search first.</p><p>From this Wiki-esque <a href="https://optimization.cbe.cornell.edu/index.php?title=Line_search_methods">page by Cornell</a> : “Line search method is an iterative approach to find a <em>local</em> minimum of a multidimensional nonlinear function using the function’s gradients. It computes a search direction and then finds an <em>acceptable step length</em> that satisfies certain standard <em>conditions</em>”.</p><p>Now, moving on the actual Line search in the TRPO, from CMU notes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*cO7R2fT0Flw4JMlpOL2qOw.png" /></figure><p>In the Appendix C of the TRPO paper, the author mentions that we need to use this line search to check the surrogate objective Lθ is improving and also to make sure the KL divergence constraint is still satisfied. They mention that this is necessary because of these are non-linear constraints and might get violated in the update step ( proposed policy update) because of the linear and quadratic series approximations used. Without this step, they found that <em>the algorithm sometimes may compute a step size that lead to abysmal performance degradation.</em></p><p>Firstly we find the direction of line search by approximately solving the equation Ax =g where A is Fisher information matrix i.e. the quadratic approximation of the KL divergence constraint. Why approximate though? due to the time and memory complexity in case of large problem to fully form A or its inverse. The <em>conjugate gradient method </em>( referenced in the final TRPO algorithm below) is able to solve Ax = b without fully forming A.</p><p>Anyway once we find the direction of line search this way, starting from a maximal step length β, we keep reducing it till it satisfies both the KL divergent constraint and the surrogate objective Lθ is improving i.e. we try to find the max β possible.</p><p>Here is the final algorithm :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GUpA8tFjTnSqfAa48fw4g.png" /><figcaption>CMU RL Notes. CG here stands for Conjugate Gridient</figcaption></figure><h3>Algorithm #5 : Proximal Policy Optimization :</h3><p>The PPO paper (OpenAI, 2017)[12] was surprisingly an easier read and I sighed a breath of relief. It starts with pointing out the limitations of existing algorithms :</p><blockquote>“Q-learning (with function approximation) fails on many simple problems and is poorly understood, vanilla policy gradient methods have poor data efficiency and robustness; and trust region policy optimization (TRPO) is relatively complicated, and is not compatible with architectures that include noise (such as dropout) or parameter sharing (between the policy and value function, or with auxiliary tasks).”</blockquote><p>They further clarify their comment regarding DQN : while it does well on discrete action spaces — it performs poorly in continuous control problems.</p><p>So, their goal to replicate the data efficiency and reliable performance of TRPO — but make it simpler — by using only first order optimization.</p><p>Now they introduced 2 new surrogate loss functions in their paper :</p><ol><li><strong>Clipped Surrogate Objective</strong> :</li></ol><p>So, PPO maximizes the below objective :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*S-5JX9lTJ0Lo-zUrDKFskQ.png" /><figcaption>PPO paper</figcaption></figure><p>where rt(θ) is the probability ratio :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*xh7JK0F493B-2rJX3Y65gQ.png" /><figcaption>PPO paper</figcaption></figure><p>But without any constraint , we could have very huge policy updates, hence they propose this new surrogate objective, penalizing whenever the old and new policies become too different, by clipping the probability ratio between 1+Є and 1-Є :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUjeY3nDkv1YmDEb2I00qw.png" /><figcaption>PPO paper</figcaption></figure><p><strong>2</strong>.<strong> Adaptive KL Penalty</strong> : Note that they mentioned this fared worse than clipped objective ; and that this could be used independently or in conjunction with the former.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Kqd0oEt3P7jktrG7Kw9tw.png" /><figcaption>PPO paper, 2017</figcaption></figure><p>The two values of 2 and 1.5 are chosen hieuristically. These help to adjust the β if the KL divergence between the old and new policies get too different from the target KL divergence ( a hyperparameter). They experimented with different values of it — 0.01. 0.03, 0.003 (listed in Table 1 of the paper).</p><p>Final algorithm : They modify the CLIP loss to arrive at the final objective, would like to simply quote them directly :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwBrmzgA6i5lXz4Qvmbk1A.png" /><figcaption>PPO paper</figcaption></figure><p>Here is a PPO implementation they mention for fixed length trajectory :</p><blockquote>“Each iteration, each of N (parallel) actors collect T timesteps of data. Then we construct the surrogate loss on these NT timesteps of data, and optimize it with minibatch SGD (or usually for better performance, Adam [KB14]), for K epochs.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewgjeB4BcQ_mWWALE27foQ.png" /><figcaption>PPO paper</figcaption></figure><p>Since the <em>Actor Critic</em> term introduced above is new in the discussion, I would like to end today’s session with a brief quote from Sutton &amp; Barto :</p><blockquote>“Actor-critic methods are TD methods that have a separate memory structure to explicitly represent the policy independent of the value function. The policy structure is known as the actor, because it is used to select actions, and the estimated value function is known as the critic, because it criticizes the actions made by the actor. ”</blockquote><p>In the next part &amp; last of the series, we will cover <strong>Actor-Critic</strong> algorithms in detail — including DDPG, which is excellent for continuous control tasks.</p><h3>References :</h3><ol><li><a href="https://www.davidsilver.uk/teaching/">Reinforcement Learning by David Silver, UCL</a></li><li><a href="https://rail.eecs.berkeley.edu/deeprlcourse-fa20/">Deep Reinforcement Learning</a> , CS 285 at UC Berkeley</li><li><a href="https://www.andrew.cmu.edu/course/10-403/">Deep Reinforcement Learning and Control</a>, CMU, Katerina Fragkiadaki</li><li>Class Notes by Dr. <a href="https://scholar.google.com/citations?user=4UB8w1AAAAAJ&amp;hl=en">Easwar Subramanian</a>, IIT Hyderabad</li><li>“<a href="http://incompleteideas.net/book/the-book-2nd.html">Reinforcement Learning: An Introduction</a>” — Richard S. Sutton and Andrew G. Barto</li><li><em>Neural Computation, </em>1998 paper, “Natural Gradient Works Efficiently in Learning” by S. Amari et al</li><li>NIPS 1999 paper — “Policy Gradient Methods for Reinforcement Learning with Function Approximation” by Richard Sutton et al</li><li><a href="https://builtin.com/articles/importance-sampling">https://builtin.com/articles/importance-sampling</a></li><li>NIPS 2001 paper — “A Natural Policy Gradient” by Sham Kakade</li><li>2015 paper, <a href="https://people.engr.tamu.edu/guni/csce642/files/trpo.pdf">Trust Region Policy Optimization</a> by John Schulman</li><li><a href="https://optimization.cbe.cornell.edu/index.php?title=Line_search_methods">https://optimization.cbe.cornell.edu/index.php?title=Line_search_methods</a></li><li>2017, “<a href="https://arxiv.org/abs/1707.06347">Proximal policy optimization algorithms</a>” by John Schulman et al</li><li>Schulman, J., Moritz, P., Levine, S., Jordan, M., &amp; Abbeel, P. (2015). High-dimensional continuous control using generalized advantage estimation. <em>arXiv preprint arXiv:1506.02438</em>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdca33709ea2" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/policy-based-deep-rl-part-2-of-reinforcement-learning-series-cdca33709ea2">Policy Based Deep RL — part 2 of Reinforcement Learning Series</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, Part 1- Model Based, Model Free & Function Approximation]]></title>
            <link>https://medium.com/@saurad44/reinforcement-learning-part-1-model-based-model-free-function-approximation-4501e317e9d6?source=rss-82fbcbdab085------2</link>
            <guid isPermaLink="false">https://medium.com/p/4501e317e9d6</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[q-learning]]></category>
            <category><![CDATA[monte-carlo]]></category>
            <category><![CDATA[dqn]]></category>
            <dc:creator><![CDATA[Sauradeep Debnath]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 18:09:55 GMT</pubDate>
            <atom:updated>2026-08-24T11:54:49.891Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>In this article, I will try to give a overview of the popular RL algos , starting from the basic definitions in RL. Next, I cover the scenarios when the system dynamics are completely known (Policy Iteration, Value Iteration) vs when they aren’t (Monte Carlo, TD, SARSA, Q-Learning). Then I reflect upon the need for <em>function approximation</em> for complex systems and then finally deep-Q-network ( DQN) .</p><p><strong>CONTENT :</strong></p><p>Basic Definitions — discount rate, value function, Markov Property, Bellman Equations, Backup diagrams</p><p><a href="#cf1e">Algorithm 1 : Policy Iteration</a></p><p><a href="#f042">Algorithm 2 : Value Iteration</a></p><p><a href="#676f">Model Free Prediction- Algorithm 3: Monte Carlo</a></p><p><a href="#41a1">Algorithm 4 : Temporal Difference (TD)</a></p><p><a href="#d18e">Model Free Control</a></p><p>Algorithm 5 : <a href="#b091">on Policy TD control : SARSA(1994)</a>:</p><p><a href="#4da9">Algorithm 6 : Off Policy TD control : Q-Learning ( Watkins, 1989)</a></p><p><a href="#ab71">Need for Function Approximation</a></p><p><a href="#9800">Algorithm 7: DQN(2013, DeepMind)</a></p><p><em>First of all we need to brush up some </em><strong><em>definitions</em></strong><em> :</em></p><ol><li><strong>Discount rate</strong> : γ is a parameter, 0&lt;γ&lt;1, called the <strong>discount rate</strong>.</li></ol><p>“a reward r received k time steps in the future is worth only γ^(k-1) times what it would be worth if it were received immediately” (thus reduced in value). Please note that return G(t) is the discounted sum of all rewards in the entire trajectory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*AGrYDY3EigrQ0jqA5KwSBA.png" /><figcaption>discounted formula for “Expected return” Gt — Sutton &amp; Barto (“S&amp;B” for short)</figcaption></figure><p>2. ʋₖ — <strong>Value function</strong> of a state : it denotes “how good” a state is in terms of expected/ future returns. Thus this could be estimated as the average over all possible trajectories’ return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*FRJ3n59FfW29u2lpznpY3w.png" /><figcaption>S&amp;B</figcaption></figure><p>Similarly, Action -value function for taking an action a at state s is denoted by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*AjIJLyZbx4YCTb7BTAMPqg.png" /><figcaption>S&amp;B</figcaption></figure><p>3. <strong>Markov Property</strong> : A state is considered Markov if at time t+1 , it only depends on the state and action at time t and older history can be ignored</p><p>4. <strong>Bellman equation</strong> for Markov Reward Processes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIETsuh2oC-dU810ne7R6w.png" /><figcaption>Bellman Equation for value function — which describes the relationship between the value of a given state and those of its successr states — Sutton &amp; Barto</figcaption></figure><p>5. <strong>Backup diagrams</strong> : These are diagrams , with time always flowing downward, that show the relationships that form update or <em>backup</em> operations that “ transfer value information back to a state (or a state-action pair) from its successor states (or state-action pairs).” ( Sutton &amp; Barto). Unlike a transition graphs, here a successor could be the current state itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*W07kkkfCzbNpDGlAUsTPuQ.png" /><figcaption>S&amp;B</figcaption></figure><h3>Case 1 : Model Based Techniques ( Dynamic Programming) :</h3><p>This is the case when we know both P( state transition probability ) and R( reward function). In <em>real life it is rarely the case </em>except for simple board games etc.</p><h3>Algorithm 1 : Policy Iteration :</h3><p>It is a loop consisting of 2 repeated steps — Policy Evaluation and Policy Improvement — till there is convergence.( Let us consider a stochastic, rather than deterministic policy for the following discussions.)</p><p><strong>Policy Evaluation </strong>is called a “<strong>Prediction”</strong> problem in Dynamic program (DP) literature. For Policy Evaluation, we could use the Bellman equation above — which would essentially become a system of |S| linear equations. While this is straight forward, it is tedious. The alternative will be solve it <em>iteratively</em>, by starting with at an arbitrary ʋ₀( except for the terminal state which has to be 0) and then using an iterative form of the Bellman equation :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkAQpYwZCWwSDGbN35LZxg.png" /><figcaption>David Silver, policy evaluation using DP</figcaption></figure><p>Here ʋₖ is the the kth approximation of value function of state s’; r is the reward; π(a|s) is the probability of taking action a in state s under policy π.</p><p>So, starting with arbitrary initial value functions, we iteratively calculate the value of a given state s , by adding the reward R at that state plus the discounted ( current ) value function of all the possible successor states s’ weighted by their probabilities of occurance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*76Zv6daLyisYHdWbDFWHlA.png" /><figcaption>David Silver, “DP”. In this game there is R=-1 for every step . γ = 1 ( undiscounted). Agent follows an uniform policy , but if any action is taking us outside the grid, we stay where we are. The grey states are the terminal states.</figcaption></figure><p>As k → infinity, ʋₖ (s) approaches ʋπ(s), the true value function of state s.( for simpler problems with fewer states and actions it might do so in very few iterations like 5 or 7 etc.)</p><p><strong>Policy Improvement</strong> <strong>Step ( “Control” Problem i.e finding an optimal policy) :</strong></p><p>At each state s, we want to proceed greedily. That is, we want to explore if we can get better returns if we take an action that might not be recommended by current policy π ( i.e. we search for a better policy) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*dCvOgXxyd2Ihs-RJCUSemQ.png" /><figcaption>S&amp;B</figcaption></figure><p>Thus these 2 steps are repeated till there is no more policy improvement.</p><h3>Algorithm 2 : Value Iteration :</h3><p>We saw above that iterative Value Iteration — which is one of the 2 repeated steps of Policy Iteration — converges only at k = ∞. But must we go all the way ? The convergence guarantee holds even we if truncate k to a small number ( generalized policy iteration/GPI is based on this idea) . One such extreme case is k=1, that is , <em>we only do only one sweep of policy evaluation</em>. This is known as Value Iteration.</p><h3>Case 2 : Model Free Techniques (“Learning”):</h3><h3>2.a Model Free Prediction :</h3><p>In this case,<em> we do not need the complete knowledge of the system, rather we can learn from experience.</em></p><p>There are 2 ways to model Free Prediction : Monte Carlo and Temporal Difference(TD). ( <strong>Algo #3 and #4</strong> in our discussion)</p><p>For <strong>Monte Carlo</strong> (first used in RL in 1968), we <em>sample the entire trajectory</em> (called an “<strong>episode</strong>” — and thus only suitable for “episodic tasks” — the ones who would terminate eventually no matter what actions are selected). “First visit MC” averages the returns from visiting the state s only the first time in the episodes, while “every visit MC” takes the other approach.</p><p>Note — for <strong><em>Off Policy</em> </strong>Monte Carlo prediction( we have the episodes from a different policy (called the “behaviour policy” μ), not the one we want to evaluate- the “target” policy π ), we would need to use <em>Importance Sampling,</em> but that’s the topic for another day 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*ubJn1z1p3LLOOcvTIfRrRA.png" /><figcaption>Sutton &amp; Barto</figcaption></figure><p>Please note that apart from the benefit of learning from experience itself, for MC,<em> the estimate of one state does not build upon the estimate of any other state</em>(no <em>bootstrapping</em>, unlike DP) .So we can generate samples <em>only from the states we are interested in</em> and average them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJLFwuljswKsX3ljYNPjJw.png" /><figcaption>S&amp;B</figcaption></figure><p><strong>Temporal Difference (TD) :</strong></p><blockquote><em>“TD learning is a combination of Monte Carlo ideas and dynamic programming (DP) ideas. Like Monte Carlo methods, TD methods can learn directly from raw experience without a model of the environment’s dynamics. Like DP, TD methods update estimates </em>based in part on other learned estimates, without waiting for a final outcome<em> (they bootstrap)”.- S&amp;B, Chapter 6.</em></blockquote><p>Thus the TD methods can be implemented in an <strong>online</strong>, incremental method , unlike MC. The update formula uses the below result from incremental definition of mean :</p><p>New Estimate = Old Estimate + Learning Rate(Target — Old Estimate)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reE1xbWb6Jj43Zf-uHDWzQ.png" /><figcaption>David Silver, Lecture 3, DP</figcaption></figure><p>Now let us apply the equations of incremental mean in case of MC &amp; TD . Note — Here R + γ V(S’) is the target for TD update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGAm81PERIRRm0wZExl1Ng.png" /><figcaption>David Silver, Lect 4</figcaption></figure><p>Thus the entire TD algorithm is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*xutjiTH1r_2-1D7udzdtUA.png" /><figcaption>S&amp;B</figcaption></figure><p>Note — both MC &amp; TD are sample backups, unlike DP, where the back up is based on a single sample successor, rather than all possible successors.</p><p>We can update the estimates not just after one step — but it can also be after any n steps (“n step TD”). We can even average the returns for multiple values of n( e.g. an weighted average of 1, 2, 3 &amp; 4 step returns) . One such algorithm, called TD(λ), weights the returns by λ^(n-1), λ Є [0,1] ; thus giving the highest weightage to the one-step return.</p><h3>2.b Model Free Control :</h3><p>Please note , while ‘prediction’ tries to evaulate how good a particular policy is, ‘control’ tries to find the optimal policy.</p><p>Here, Policy improvement is done by being greedy wrt. the current action-value function ( i.e. taking argmax )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*rMoSsSjFxx3_qjK2MrYe9g.png" /><figcaption>S&amp;B. Exploring Starts denotes the assumption that each state has a non zero probability of being selected at the start. This however, might not be true practically in many situations.</figcaption></figure><p>Next we will cover two popular TD Control algorithms called SARSA ( on- policy) and Q-Learning ( off-policy, precursor to DQN !)</p><h3>Algo 5 : on Policy TD control : SARSA(1994):</h3><p>It again follows the pattern of generalized policy iteration ( GPI). but using TD for the Prediction/Evaluation part. For the Policy Improvement part, we could be greedy or ε-greedy ( when we choose greedily with 1-ε probability, and uniformly randomly with ε probability) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*UXK7So5Hnx2Do7aOzvSsJQ.png" /><figcaption>SARSA, SB</figcaption></figure><h3>Algo 6 : Off Policy TD control : Q-Learning ( Watkins, 1989) :</h3><p>Sutton &amp; Barto describe it as “One of the most important breakthroughs in reinforcement learning”. Note — No importance sampling is required here.</p><p>Here , we can directly estimate the optimal value function q* , irrespectively of the policy being followed — because during the update step, we maximize over all possible actions possible from next state S’. This enables early convergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_Euat7tbaIHmRwPz7s36A.png" /><figcaption>David Silver, “model free control”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*Q00EgiPCBOH_2UmiKrecnQ.png" /><figcaption>S&amp;B</figcaption></figure><h3>Case 3 : Need for Function Approximation :</h3><p>So far we have been seeing cases where we are <em>storing the estimates of each state or action-state pairs. </em>But this is not practical in case of<em> continuous variables or complex sensory input</em> like an image. Then we need to find a way to <em>generalize</em> the value functions<em> even for states it hasn’t seen before.</em></p><p>We could use some sort of supervised learning. However, firstly we need a model that can learn online/incrementally, rather than on stationary dataset. Secondly, we need to handle the problem of non-stationary target.</p><p>“For example, in GPI control methods we often seek to learn q π while π changes. Even if the policy remains the same, the target values of training examples are nonstationary if they are generated by bootstrapping methods (DP and TD)”( Sutton &amp; Barto)</p><h3>Algo 7 : DQN(2013, DeepMind):</h3><p>The deep-Q-network introduced in the “Playing Atari with Deep Reinforcement Learning””paper was a game changer. It was the first time, we had a control algorithm that could learn from complex visual stimuli as input — in this case of high dimensional visual input (210 x 160 RGB video at 60Hz) of the Atari 2600 game — without any game specific/emulator specific info or hand crafted visual features. <em>Using Convolutional neural nets as the function approximator, it achieved state-of-art in 6 of 7 Atari games</em>, while in the 7th game ( “Invader”) , HNeat, using hand crafted object detectors for objects in Atari games , took the first place.</p><p><em>Now going into the DQN implementation</em>. Note — in the below example ,we assume Qφ is a deep neural network with parameter φ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbBHHFxKOaBN4EL8xszrnQ.png" /><figcaption>IIT Hyd Class Notes by Dr Easwar</figcaption></figure><p>Firstly, if we just convert the earlier Q learning into an online/incremental version, we can easily see that the convergence guarantees don’t hold due to non-stationary targets(#issue 1) — and not to mention the collected samples will be sequentially correlated, as they are collected one after another (#issue 2):</p><p>DQN solved these by introducing 2 key ideas :</p><ol><li>Replay buffer ( for data correlation) : Borrowing the idea from Fitted Q iteration, we store the experiences in a replay buffer of size N. When the buffer is full, the oldest experience is deleted ( FIFO). We sample random mini-batches of size B from here.</li><li>To handle the moving data problem, we create a second Target Network.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*K21PnJZHvkEoR-Zu" /><figcaption>IIT Hyd class Notes by Dr. Easwar</figcaption></figure><p>In their 2015 paper published in “nature”, Minh et al also mentioned that they achieved greater training stability by clipping the error terms (Qφ (s,a) — “target”) between -1 and 1.</p><h3>References :</h3><ol><li>“<a href="http://incompleteideas.net/book/the-book-2nd.html">Reinforcement Learning: An Introduction</a>” — Richard S. Sutton and Andrew G. Barto ( referenced as “S&amp;B” for brevity)</li><li>Mnih, V. (2013).<a href="https://arxiv.org/abs/1312.5602"> Playing atari with deep reinforcement learning</a>. <em>arXiv preprint arXiv:1312.5602</em>.</li><li><a href="https://www.nature.com/articles/nature14236">Human-level control through deep reinforcement learning,</a> published 25 February 2015</li><li><a href="https://www.davidsilver.uk/teaching/">Reinforcement Learning by David Silver, UCL</a></li><li><a href="https://rail.eecs.berkeley.edu/deeprlcourse-fa20/">Deep Reinforcement Learning</a> , CS 285 at UC Berkeley</li><li>Class Notes by Dr. <a href="https://scholar.google.com/citations?user=4UB8w1AAAAAJ&amp;hl=en">Easwar Subramanian</a>, IIT Hyderabad</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4501e317e9d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Challenges of RAG Evaluation — A journey exploring 35+ relevant NLP/LLM papers from 2016–2024]]></title>
            <link>https://medium.com/@saurad44/the-challenges-of-rag-evaluation-a-journey-exploring-35-relevant-nlp-llm-papers-from-2016-2024-63bf421ff91a?source=rss-82fbcbdab085------2</link>
            <guid isPermaLink="false">https://medium.com/p/63bf421ff91a</guid>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[llm-benchmarks]]></category>
            <dc:creator><![CDATA[Sauradeep Debnath]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 06:51:37 GMT</pubDate>
            <atom:updated>2025-09-01T14:18:31.354Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Challenges of RAG Evaluation — A journey exploring 35+ relevant NLP/LLM papers from 2016–2024</h3><p>Building a question-answering system is a pretty ubiquitous problem these days. Every organization has piles of unstructured data, and you want to build some sort of LLM application on top of it .</p><p>Content:</p><ol><li><a href="#a31d">Challenges</a></li></ol><p>2. <a href="#a1a5">Phase 1 of Journey : Exploring popular benchmarks :</a></p><p>3. <a href="#7be7">Phase 2 : Finding Subjective, open-ended answer specific benchmarks from Llama 3.1 paper :</a></p><p>4. <a href="#9688">Phase 4: RAGAS, ARES &amp; others :</a></p><p>5. <a href="#07a4"><em>Phase 5 : DeepEval : QAG ( Question Answer Generation )</em></a>:</p><h3>Challenges:</h3><p><em>There are a lot challenges associated with evaluating RAG systems </em>:</p><p>a. in many of the cases, unlike, the popular benchmarks, we are looking for a subjective/open ended answer, not a MCQ or one word, fill-in- the-blank answer.</p><p>b. To make things more complicated, if I ask a question regarding topic X, and there are multiple references to X in the Vector DB, the generated answer may be a combination of the styles and information from multiple /all of them — thus it may match in terms of content to the reference answer , but almost never guaranteed to have a word-to-word match.</p><p>c. The reference answers can also be highly subjective, depending on the SME who wrote it.</p><p>d. On the top of that, LLMs tend to explain the relevant jargons/background in greater details, while an SME crafted reference answer can often be to the point.</p><p>e. Collecting reference answers is expensive.</p><p>So, to solve this problem, I wanted to look for any useful insights in the “popular” benchmarks found in the papers/technical reports of the state-of-the-art models like GPT-4/4–o/4-o1/Sonnet 3.5/Llama3.1 , a journey spanning from SQuAD(2016) to more recent RAG specific papers in 2023/24.</p><h3>Phase 1 of Journey : Exploring popular benchmarks :</h3><p>I first tried to understand all the existing popular benchmarks in depth, especially the ones that haven’t turned obsolete yet.<strong> Here are </strong><a href="https://medium.com/@saurad44/all-about-llm-benchmarks-2021-series-c0cc61dd9226"><strong>part 1</strong></a><strong> and </strong><a href="https://medium.com/@saurad44/evaluating-llms-all-about-llm-benchmarks-part-2-years-2022-24-cf11c448b544"><strong>part 2</strong></a><strong> of my key takeaways</strong>.</p><p>However, soon I realized <strong><em>most of these popular benchmarks aren’t really relevant to subjective/open ended question answering</em></strong>. E.g. ARC(2018), MMLU(ICLR 2021), MMLU-Pro(2024), GPQA(2024) are Multiple Choice Questions(MCQs)- Thus they can simply check for classification accuracy. For MATH ( NeurIPS 2021) , final answer is a number delimited with the \boxed{} command. GSM8k(2021) and MathQA-Python(2021) are also evaluated by exact match due to having a numerical answer. AGIEval(2023) has a mix of MCQs and fill in the blank questions. For IFEval(2023), the evaulation is done via heuristics post pre processing. For coding benchmarks like HumanEval(2021) &amp; MBBP(2021), they check for “functional correctness” i.e. the number of test cases passed.</p><h3>Phase 2 : Finding Subjective, open-ended answer specific benchmarks from Llama 3.1 paper :</h3><p>In the Llama3.1 paper(2024), however, out of the 3 reading comprehension benchamarks mentioned , SQuAD and QuAC benchmarks did have subjective answers — just like we wanted whereas RACE( 2017, CMU) again had MCQ format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eoi3w1CBe9QyCWIf8cN0UA.png" /><figcaption>Reading Comprehension benchmarks from Llama3.1 paper</figcaption></figure><p><strong>SQuAD: Stanford Question Answering Dataset</strong> ( EMNLP 2016, Stanford, 100k questions ) — it uses two evaluation metrics : Exact Match and macro averaged F1 score over the tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNiHtHiBEsvajdKM801mzQ.png" /><figcaption>Sample Q&amp;A from SQuAD</figcaption></figure><p><strong>QuAC : Question Answering in Context( 2018)</strong> again uses averaged F1 score, just like SQuAD(<em> post removing stop words</em> ). They also propose a new metric called human equivalent score (HEQ)</p><blockquote>“HEQ measures the percentage of examples for which system F1 exceeds or matches human F1. “</blockquote><p>Similarly, Llama 3.1 paper mentions 3 benchmarks for long context understanding :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yKTyJgu6OdHhhsKLqui-g.png" /><figcaption>Llama 3.1 benchmark table screenshot</figcaption></figure><p><strong>ZeroSCROLLS</strong> (2023)— uses F1 score for Q&amp;A, Accuracy for MCQs, ROUGE for summarization. ∞<strong>BENCH</strong> (2024 Feb)uses ROUGE-L-sum for summarization ; while relying on exact match for a number of tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*YG6VdjBLlfaamSXV7Z1a5A.png" /><figcaption>InfiniteBench paper : comparison with existing long context benchmarks — en &amp; zh here means english and chinese respectively. “Avg Len” here means the number of tokens in the context</figcaption></figure><p><strong>LongBench</strong>(2023 Aug) used F1 for Q&amp;A, ROUGE-L for summarization &amp; edit similarity(<a href="https://en.wikipedia.org/wiki/Levenshtein_distance"> Levenstein distance</a>) for code completion.</p><p><strong>L Eval</strong><em>(</em>2023 July/Oct) states that their experiments show that <em>LLM Judges</em> are better than n-gram based metrics( e.g. F1 score) for open-ended tasks, when compared to human judgement and relatively more robust to the problem of getting a lower score in longer output length . Check out their <a href="https://github.com/OpenLMLab/LEval/blob/main/Evaluation/llm_eval.py">github</a> for their <strong>prompt</strong> for<em> LLM eval</em> for comparing reference and generated answer.</p><p>Lastly, <strong>Needle-in-a-Haystack</strong>(2023) they don’t have a paper yet but in their github <a href="https://github.com/gkamradt/LLMTest_NeedleInAHaystack/blob/main/tests/test_evaluators.py">evaluation code</a> invoke a custom class called <a href="https://github.com/gkamradt/LLMTest_NeedleInAHaystack/blob/main/needlehaystack/evaluators/openai.py">OpenAIEvaluator</a> where they score the answer the following way</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*8EUiyg5co4O2LZUaPYRfyg.png" /><figcaption>Needle in a haystack — OpenAI Evaluator</figcaption></figure><h3>Phase 3 : Exploring latest RAG papers :</h3><p><strong><em>Self RAG(2023 Oct)</em></strong> -for short answer generation, they score it based on if “gold answers” are included in the generated answer instead of strict exact matching. For long answers, they use FactScore (2023) &amp; MAUVE (2021)</p><p><strong><em>Corrective RAG(2024 Jan)</em> </strong>-uses accuracy for MCQs, True/False and short form generation tasks &amp; FactScore(2023) for long form generation tasks</p><p><strong>Adaptive RAG(2024 March) </strong>— uses F1, EM(exact match), and Accuracy (Acc) calling it “the standard evaluation protocol” while clarifying that Acc measures if the generated answer contains the ground-truth/reference answer.</p><p>Now let us try to understand this FactScore metric.</p><p><strong>FActScore</strong> : Fine-grained Atomic Evaluation of Factual Precision in Long Form Text Generation( 2023) : As the title suggests, first we break down the answer into atomic facts — which they define as a short sentence containing only one piece of information. Then we check how many of these atomic facts are correct as per a reliable knowledge source.</p><p>For generating the atomic facts, they invoke InstructGPT (text-davinci-003) with the following <strong>prompt</strong> : “Please breakdown the following sentence into independent facts: ” followed by multiple few-shot examples.</p><p><strong>MAUVE</strong>: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers (NeurIPS 2021) :</p><p>This score is used for open ended text generation. So assume P is the target distribution and Q is the model generated distribution. Then Type I (false positive) and Type II (false negative) can be denoted by <a href="https://machinelearningmastery.com/divergence-between-probability-distributions/">KL div</a> (Q|P) and KL div (P|Q) respectively.</p><p>the divergence curve is defined by :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*8ha5Z14VPo2xU1pV7aW4-A.png" /><figcaption>MAUVE — divergence curve</figcaption></figure><p>MAUVE score is nothing but the area under the divergence curve. It is available under <a href="https://huggingface.co/spaces/evaluate-metric/mauve">huggingface evaluation metrics</a></p><h3>Phase 4: RAGAS, ARES &amp; others :</h3><p>Before diving into RAGAS itself, here are some of the related metrics mentioned in the RAGAS paper: FactScore(2023)- already covered.</p><p><em>BERTScore(2020), MoverScore(2019)</em> — uses embedding similarity between generated and reference answers.</p><p><em>BARTScore(2021, CMU)</em> — Unsupervised metric; fine tunes BART on generation based problems . That is, just like PRISM( EMNLP 2020) , BARTScore looks at evaluation as a text generation problem in stead of the more common approaches of unsupervised matching(as done in<em> </em>BERTScore, MoverScore,<em> </em>BLEU(2002), ROUGE, CHRF(2015)<em> </em>) or supervised regression (COMET- EMNLP 2020 , BLEURT- ACL 2020) or supervised ranking ( COMET, BEER) .</p><p>It calculates recall i.e. P( reference/generated) and precision i.e. P(generated /reference) , faithfulness( generated/source).</p><p><em>SelfCheckGPT(2023)</em> — sample multiple answer &amp; check the semantic similarity, assuming factual answers must be more stable than hallucinations.</p><p><em>GPTScore : </em>Evaluate as You Desire <em>(2023) </em>— Prompt based, customized, training free, 0 shot evaluation. Given task description d ( e.g. summarization) and aspect definition ( e.g. factuality), hypothesis/generated text h and source/reference text S , it is defined as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*9wkey2JtRLgfeE0sQnnZoQ.png" /><figcaption>GPTScore formula</figcaption></figure><p>also mention worthy — using ChatGPT to give a score between 0 to 100 or 1 to 5 stars.( from the 2023 paper “Is chatgpt a good NLG evaluator? A preliminary study.”)</p><p><strong>RAGAS (2023, March) </strong>: RAGAS has a number of <strong>prompt</strong> based metrics —first 3 of them can be computed even at the expense of reference answers ( which is very expensive) :</p><ol><li>Faithfulness : the answer should be grounded in the context</li><li>Answer relevance : answer should be actually answering to the user question ( checked via comparing it with hypothetical questions generated from the answer)</li><li>Context relevance : the fetched contexts should be precise and should have as little irrelevant info as possible- so as not to confuse the LLM ( checked by first extracting the list of sentences in the context that are actually useful to answer the question)</li></ol><p><a href="https://docs.ragas.io/en/latest/concepts/metrics/index.html">The RAGAS website</a> also lists down other reference answer based metrics like answer similarity, answer correctness( which bears a lot of similarity to FactScore) etc .— but they are not mentioned in the paper.</p><h3>ARES (2023 Sept/2024 March, Stanford) :</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yw7sa6ge0gHF2v20u8S6g.png" /><figcaption>ARES overview</figcaption></figure><p><em>ARES achieved an impressive improvement of 59.3% and 14.4% as compared t RAGAS( and 0.065 and 0.132 higher Kendall’s τ correlation coefficient between the correct ranking and predicted ranking) </em>respectively in terms of context relevance and answer relevance in KILT &amp; SuperGLUE datasets. In stead of hard coded prompts as used in RAGAS, it uses 3 fine tuned LM Judges. ARES was also reported to have Kendall’s tau 0.06 higher over both of both of these metrics for GPT-3.5 judge ( no experiment was done for GPT-4 judge due to higher cost)</p><p>Firstly using 5(or more ) expert-crafted in-domain Q&amp;A pair as few shot examples, it leverages <em>FLAN-T5 XXL</em>(2022, 11.3B params) to create (positive) question-answer pairs from the dataset. For the negative examples of the 3 metrics, they employ strategies like random sampling or say, purposefully generating a contradictory answer with LM. They first fine tune the three <em>DeBERTa-v3-Large</em>(2021, 304M) judges on these examples, each judge being a binary classifier.</p><p>It is next also fine tuned on the much smaller set of around 150 human data annotations for positive &amp; negative examples of positive/negative values of the 3 metrics ( the 3rd metric being answer faithfulness).</p><p>Finally, a RAG confidence bound is created by used a recent statistical method called prediction-powered inference/<strong>PPI</strong>( 2023)</p><blockquote>“PPI is a recent statistical method that provides tighter confidence intervals on a small set of annotated datapoints (i.e., our validation set) by leveraging predictions on a much larger set of non-annotated datapoints.”</blockquote><p>The RAG systems are finally ranked using the middle point of the confidence interval.</p><p>Last but not the least :</p><h3>Phase 5 : DeepEval : QAG ( Question Answer Generation ):</h3><blockquote>“<em> we’re using QAG for all RAG metrics</em>”- DeepEval</blockquote><p>DeepEval is one of the most popular LLM Eval metrics as of now, mid 2025. The sheer variety and trustworthiness of the metrics, as well as the fact that a reasoning is provided for the score — are some of the reasons for all the love it is getting. For a detailed understanding of QAG works specifically in case of DeepEval, please check out their blog (<a href="https://www.confident-ai.com/blog/a-step-by-step-guide-to-evaluating-an-llm-text-summarization-task">https://www.confident-ai.com/blog/a-step-by-step-guide-to-evaluating-an-llm-text-summarization-task</a> ).</p><p>In short, rather than asking LLM to give a direct score on a task ( like summarization, say where we want to evaluate the factual correctness) — which can lead to arbitrary &amp; biased result, QAG does something smarter. Much like, FactScore above, it asks the LLMs to create close ended questions ( e.g. questions that can be answered by ‘yes’, ‘no’, ‘idk’). Now, the LLM would be asked to answer them based on both reference text and actual AI output. ( or so on, depending on the exact metric).</p><p>A final score is calculated mathematically, based on how each of these close-ended sub questions fare — thus leading to a more reliable score.</p><p>That’s it for today !</p><h3>References :</h3><ol><li>Dubey, A., Jauhri, A., Pandey, A., Kadian, A., Al-Dahle, A., Letman, A., … &amp; Ganapathy, R. (2024). The llama 3 herd of models. <em>arXiv preprint arXiv:2407.21783</em>.</li><li>Rajpurkar, P. (2016). Squad: 100,000+ questions for machine comprehension of text. <em>arXiv preprint arXiv:1606.05250</em>.</li><li>Lai, G., Xie, Q., Liu, H., Yang, Y., &amp; Hovy, E. (2017). Race: Large-scale reading comprehension dataset from examinations. <em>arXiv preprint arXiv:1704.04683</em>.</li><li>Choi, E., He, H., Iyyer, M., Yatskar, M., Yih, W. T., Choi, Y., … &amp; Zettlemoyer, L. (2018). QuAC: Question answering in context. <em>arXiv preprint arXiv:1808.07036</em>.</li><li>Shaham, U., Ivgi, M., Efrat, A., Berant, J., &amp; Levy, O. (2023). Zeroscrolls: A zero-shot benchmark for long text understanding. <em>arXiv preprint arXiv:2305.14196</em>.</li><li>Zhang, X., Chen, Y., Hu, S., Xu, Z., Chen, J., Hao, M., … &amp; Sun, M. (2024, August). ∞ Bench: Extending Long Context Evaluation Beyond 100K Tokens. In <em>Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)</em> (pp. 15262–15277).</li><li>Bai, Y., Lv, X., Zhang, J., Lyu, H., Tang, J., Huang, Z., … &amp; Li, J. (2023). Longbench: A bilingual, multitask benchmark for long context understanding. <em>arXiv preprint arXiv:2308.14508</em>.</li><li>An, C., Gong, S., Zhong, M., Zhao, X., Li, M., Zhang, J., … &amp; Qiu, X. (2023). L-eval: Instituting standardized evaluation for long context language models. <em>arXiv preprint arXiv:2307.11088</em>.</li><li><a href="https://github.com/gkamradt/LLMTest_NeedleInAHaystack/blob/main/README.md">https://github.com/gkamradt/LLMTest_NeedleInAHaystack/blob/main/README.md</a></li><li>Asai, A., Wu, Z., Wang, Y., Sil, A., &amp; Hajishirzi, H. (2023). Self-rag: Learning to retrieve, generate, and critique through self-reflection. <em>arXiv preprint arXiv:2310.11511</em>.</li><li>Yan, S. Q., Gu, J. C., Zhu, Y., &amp; Ling, Z. H. (2024). Corrective retrieval augmented generation. <em>arXiv preprint arXiv:2401.15884</em>.</li><li>Jeong, S., Baek, J., Cho, S., Hwang, S. J., &amp; Park, J. C. (2024). Adaptive-rag: Learning to adapt retrieval-augmented large language models through question complexity. <em>arXiv preprint arXiv:2403.14403</em>.</li><li>Min, S., Krishna, K., Lyu, X., Lewis, M., Yih, W. T., Koh, P. W., … &amp; Hajishirzi, H. (2023). Factscore: Fine-grained atomic evaluation of factual precision in long form text generation. <em>arXiv preprint arXiv:2305.14251</em>.</li><li>Pillutla, K., Swayamdipta, S., Zellers, R., Thickstun, J., Welleck, S., Choi, Y., &amp; Harchaoui, Z. (2021). Mauve: Measuring the gap between neural text and human text using divergence frontiers. <em>Advances in Neural Information Processing Systems</em>, <em>34</em>, 4816–4828.</li><li>Es, S., James, J., Espinosa-Anke, L., &amp; Schockaert, S. (2023). Ragas: Automated evaluation of retrieval augmented generation. <em>arXiv preprint arXiv:2309.15217</em>.</li><li>Fu, J., Ng, S. K., Jiang, Z., &amp; Liu, P. (2023). Gptscore: Evaluate as you desire. <em>arXiv preprint arXiv:2302.04166</em>.</li><li>Yuan, W., Neubig, G., &amp; Liu, P. (2021). Bartscore: Evaluating generated text as text generation. <em>Advances in Neural Information Processing Systems</em>, <em>34</em>, 27263–27277.</li><li>Saad-Falcon, J., Khattab, O., Potts, C., &amp; Zaharia, M. (2023). Ares: An automated evaluation framework for retrieval-augmented generation systems. <em>arXiv preprint arXiv:2311.09476</em>.</li><li>Wang, A., Cho, K., &amp; Lewis, M. (2020). Asking and answering questions to evaluate the factual consistency of summaries. <em>arXiv preprint arXiv:2004.04228</em>.</li><li><a href="https://www.confident-ai.com/blog/llm-evaluation-metrics-everything-you-need-for-llm-evaluation">https://www.confident-ai.com/blog/llm-evaluation-metrics-everything-you-need-for-llm-evaluation</a></li><li>Explanation of how QAG is used in DeepEval metrics — <a href="https://www.confident-ai.com/blog/a-step-by-step-guide-to-evaluating-an-llm-text-summarization-task">https://www.confident-ai.com/blog/a-step-by-step-guide-to-evaluating-an-llm-text-summarization-task</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63bf421ff91a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating LLMs : All about LLM Benchmarks , Part 2-Years 2022–24]]></title>
            <link>https://medium.com/@saurad44/evaluating-llms-all-about-llm-benchmarks-part-2-years-2022-24-cf11c448b544?source=rss-82fbcbdab085------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf11c448b544</guid>
            <category><![CDATA[llm-benchmarks]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Sauradeep Debnath]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 13:21:50 GMT</pubDate>
            <atom:updated>2024-09-18T21:36:53.639Z</atom:updated>
            <content:encoded><![CDATA[<h3>Evaluating LLMs : Part 2,All about LLM Benchmarks fromYears 2022–24</h3><p>In my previous <a href="https://medium.com/@saurad44/all-about-llm-benchmarks-2021-series-c0cc61dd9226">article</a> , we talked about a few important LLM benchmarks that came out in 2021 -MMLU, HumanEval, MBBP, Math QA Python, MATH and GSM8k.</p><p>In this article, we will talk about some more recent LLM Benchmarks, this time in the reverse chronological order. But before that, here is the list of benchmarks mentioned in the <a href="https://openai.com/index/learning-to-reason-with-llms/">OpenAI GPT-o1 paper</a> to pique your interest :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*3n59i3HA4ViMLpm9DliG-w.png" /><figcaption>GPT-o1 performance in various benchmarks</figcaption></figure><p>Now let’s deep dive into the selected benchmarks of 2022–2024 :</p><p>MMLU-Pro, Chatbot Arena, GPQA, IFEval, AGIEval, Big Bench Hard, MGSM.</p><h3>1.MMLU-Pro, June 2024, mostly by University of Waterloo folks :</h3><p><strong><em>Comparison with MMLU</em></strong> : MMLU(2021) was mostly knowledge driven , whereas MMLU-Pro is more complex reasoning based, a fact attested by its higher performance with Chain of Thought (CoT) , unlike the original MMLU. It also expanded the MCQ number of choices from 4 to 10, both factors contributing to a drop of 16% to 33% drop in performance by LLM(s).</p><p><strong><em>Why we need MMLU Pro</em></strong> : since GPT-4 came out in March 2023, for all the SOTA models , MMLU accuracy has been confined to the range 86–87%, while showing significant (10+%) in more challenging benchmarks like MATH(2021) and Chatbot Arena (2024). That led the authors to conclude that perhaps MMLU is slowly becoming obsolete as well. And the other benchmarks for general intelligence like AGIEval(2023), ARC(2018), BBH(2022) are not broad-spectrum enough. Hence this new benchmark.</p><p><strong><em>Dataset description</em></strong> : 12k questions from 14 subjects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*0LCDw_2nPvjuUnqyoQ9pUw.png" /><figcaption>Fig : MMLU Pro dataset distribution, from the paper. The Initial Filtering involves removes questions that are “too easy”, that is , MMLU questions answered by more than 4 out of the 8 deployed LLMs. GPT-4 Turbo was used to create MCQs from STEM &amp; TheoremQA as well as to increase the number of options from 4 to 10</figcaption></figure><h3>2. Chatbot Arena, Mar 2024 , mostly by UC Berkley folks :</h3><p>Unlike most other benchmarks, Chatbot Arena and <em>Codeforces</em> are live, not static. Just like<em> MT-Bench(NeurIPS 2023)</em> and <em>AlpacaEval(2023)</em> ( both of which actually uses GPT-4 to simulate human judgement), the evaluation is based on <em>human preference</em>, not ground truth. There are 100k pairwise votes collected via crowd sourcing via generating 2 answers to user questions using 2 anonymous LLMs and then taking and analyzing user votes.</p><p>NOTE — this benchmark was created by the <em>same Chatbot Arena website</em> which came out with <em>LMSYS-CHAT-1M (2023)</em> which has just user conversations without user preferences — which is used as a LLM safety due to containing toxic, upsetting chats which could potentially jailbreak even the leading LLMS</p><h3>3. GPQA: A Graduate-Level Google- Proof Q&amp;A Benchmark, Nov 2023 by NYU, Cohere, Anthropic :</h3><p>This dataset contains very difficult MCQs ( Multiple Choice Questions) from physics, chemistry and biology written by people having or pursuing PhDs in the given domain ( called “experts”). The experts were given instructions to create questions of such difficulty that non-experts would not be able to answer even with the help of the internet (excepting LLM access). They were encouraged to use technical jargons, cover topics that are commonly misunderstood or misused topics, a newly settled controversy, implicit domain-specific practices not covered in textbooks etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*MMyuD6aBFCTwlpiGbJzFbQ.png" /><figcaption>A screenshot from GPQA paper describing the dataset difficulty</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*6tE8YmTclop7x_0xbf69jw.png" /><figcaption>A sample question from GPQA</figcaption></figure><p><em>Evaluation Criteria</em>— exact match, because of the MCQ format.</p><h3>4. IFEval, PAPER — Instruction-Following Evaluation for Large Language, 2023 Nov by Google :</h3><p>It has 25 objectively &amp; automatically “verifiable instructions” ( not ambiguous to verify ) such as “write in more than N words /sentences /paragraphs” and “mention the keyword X 3 times”. There are 500 prompts, with each prompt containing one or more verifiable instructions. For each instruction , they created multiple versions, both in terms of its parameters (such as: write in 400 to 450 words vs. in 300 to 350 words), and how it’s worded (such as: write 450 to 500 words vs. your response must contain 450 to 500 words). Other examples include — Start with/End with, Change cases, detectable format like JSON</p><p><em>Evaluation Criteria</em>— the instruction verification is checked via simple heuristics and programming. However, to combat false neagtives, they also propose a loose accuracy score where they do the above checks post any of the following transformations : remove Markdown characters like “*” and “**”., removing the first line (e.g. “Sure, here it is:”)/last line (e.g. “Hope it helps.”).</p><h3>5. AGIEval, April 2023 by Microsoft :</h3><p>These are 8k MCQs and fill-in-the-blank questions collected from standardized exams like GRE &amp; GMAT (from AQaA-RAT dataset, 2017), law school admission test, lawyer qualification test, Chinese College entrance exam ( Gaokao), Chinese Civil Services exams (leveraging JEC-QA, 2020; LogiQA, 2021), math exams like AMC, AIME etc. taken from MATH dataset. <em>Evaluation Criteria</em> : Classification accuracy for the MCQs and exact match(EM) and F1 for the fill-in-the-blank questions.</p><h3>6. Big Bench Hard, Oct 2022 and Big Bench, June 2022 :</h3><p>Big Bench — “Beyond the Imitation Game” benchmark has 204 very diverse, and challenging tasks put together by 450 authors in 132 institutions. Personally out of all the benchmark papers I have read, I have never found anything else even remotely this creative and fascinating in terms of the tasks !</p><p><em>Evaluation metrics </em>: 80% of them are JSON based — with input and output pairs and the performance being judged by standard metrics like ROUGE in some cases, or in case of MCQ(s) — where we take a classification approach, <a href="https://www.statisticshowto.com/brier-score/">Brier score</a> &amp; <a href="https://www.youtube.com/watch?v=NDY2fH1FitQ">Expected Calibration Error(ECE)</a> calculated based on model probabilities for each class.</p><p>Rest 20% of them are python programs that can query the model repeatedly/ have a dialogue( and have custom metrics) , e.g. in tasks like the popular game of <a href="https://github.com/google/BIG-bench/blob/main/bigbench/benchmark_tasks/twenty_questions/README.md">twenty questions</a>.</p><blockquote>“Task topics are diverse, drawing problems from linguistics, childhood development, math, common-sense reasoning, biology, physics, social bias, software development, and beyond.”</blockquote><p>Some other examples include, <a href="https://github.com/google/BIG-bench/blob/main/bigbench/benchmark_tasks/cause_and_effect/README.md">cause_and_effect</a> task where given 2 statements the model has to identify the cause ;<a href="https://github.com/google/BIG-bench/blob/main/bigbench/benchmark_tasks/language_identification/README.md"> language identification task </a>covering extremely low resource 1000 languages; 6 tasks for identifying social bias. The <a href="https://github.com/google/BIG-bench/blob/main/bigbench/benchmark_tasks/checkmate_in_one/README.md">checkmate_in_one_move</a> task presents the history of the moves so far in a game of chess (in algebraic notation) and prompts the model to make a move that will lead to an immediate checkmate.</p><p><strong><em>Big Bench Hard </em></strong>: A few months later, in Oct 2022, in a paper titled “<em>Challenging BIG-Bench tasks and whether chain-of-thought can solve them</em>” by Google Research &amp; Stanford selected 23 hard tasks from Big Bench — where even the best performing model could not reach human performance — and called it Big Bench Hard. One of their key takeaways was that the LLM performance on these tasks gets a huge boost if they use CoT in stead of vanilla Few shot prompting as done in the original Big Bench paper. ( only for sufficiently large model sizes ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fgQVZpH78W2QigWozbK4-g.png" /><figcaption>Examples from BBH benchmark. With few-shot CoT , OpenAI’s code-davinci-002 reached human level performance in 17 of the 23 tasks.</figcaption></figure><p>Some other interesting tasks from BBH include the <a href="https://github.com/google/BIG-bench/tree/main/bigbench/benchmark_tasks/web_of_lies">Web of Lies</a> ,<a href="https://github.com/google/BIG-bench/tree/main/bigbench/benchmark_tasks/snarks">snarks</a> for sarcasm detection, <a href="https://github.com/google/BIG-bench/tree/main/bigbench/benchmark_tasks/ruin_names">ruin-names</a> for humour detection, <a href="https://github.com/google/BIG-bench/tree/main/bigbench/benchmark_tasks/tracking_shuffled_objects">tracking shuffled objects</a>, <a href="https://github.com/google/BIG-bench/tree/main/bigbench/benchmark_tasks/temporal_sequences">temporal-sequences</a> — where, given a list of activities a person has done in certain time frames, we are asked when they might have done another task — not mentioned so far.</p><h3>7. MGSM Oct 2022, PAPER — “Language Models are Multilingual Chain-of-Thought Reasoners” by Google, Stanford etc</h3><p>The same <strong>250</strong> problems from GSM8K(2021) are each manually translated via human annotators into 10 languages- — Bengali (BN), Chinese (ZH), French (FR), German (DE), Japanese (JA), Russian (RU), Spanish (ES), Swahili (SW), Telugu (TE), and Thai (TH). The dataset was created to support the task of question answering on basic mathematical problems that require multi-step reasoning.</p><p>That’s it for today. In the next and last article of this Benchmark series, we will cover some important benchmarks from Pre-2021 that still remain relevant today like HellaSwag, ARC , DROP, WinoGrande etc.</p><h3>References :</h3><ol><li>Wang, Y., Ma, X., Zhang, G., Ni, Y., Chandra, A., Guo, S., … &amp; Chen, W. (2024). Mmlu-pro: A more robust and challenging multi-task language understanding benchmark. <em>arXiv preprint arXiv:2406.01574</em></li><li>Chiang, W. L., Zheng, L., Sheng, Y., Angelopoulos, A. N., Li, T., Li, D., … &amp; Stoica, I. (2024). Chatbot arena: An open platform for evaluating llms by human preference. <em>arXiv preprint arXiv:2403.04132</em>.</li><li>Zheng, L., Chiang, W. L., Sheng, Y., Li, T., Zhuang, S., Wu, Z., … &amp; Zhang, H. (2023). Lmsys-chat-1m: A large-scale real-world llm conversation dataset. <em>arXiv preprint arXiv:2309.11998</em>.</li><li>Rein, D., Hou, B. L., Stickland, A. C., Petty, J., Pang, R. Y., Dirani, J., … &amp; Bowman, S. R. (2023). Gpqa: A graduate-level google-proof q&amp;a benchmark. <em>arXiv preprint arXiv:2311.12022</em>.</li><li>Zhou, J., Lu, T., Mishra, S., Brahma, S., Basu, S., Luan, Y., … &amp; Hou, L. (2023). Instruction-following evaluation for large language models. <em>arXiv preprint arXiv:2311.07911</em>.</li><li>Zhong, W., Cui, R., Guo, Y., Liang, Y., Lu, S., Wang, Y., … &amp; Duan, N. AGIEval: A human-centric benchmark for evaluating foundation models. CoRR, abs/2304.06364, 2023. doi: 10.48550. <em>arXiv preprint arXiv.2304.06364</em>.</li><li>Srivastava, A., Rastogi, A., Rao, A., Shoeb, A. A. M., Abid, A., Fisch, A., … &amp; Wang, G. (2022). Beyond the imitation game: Quantifying and extrapolating the capabilities of language models. <em>arXiv preprint arXiv:2206.04615</em>.</li><li>Suzgun, M., Scales, N., Schärli, N., Gehrmann, S., Tay, Y., Chung, H. W., … &amp; Wei, J. (2022). Challenging big-bench tasks and whether chain-of-thought can solve them. <em>arXiv preprint arXiv:2210.09261</em>.</li><li>Shi, F., Suzgun, M., Freitag, M., Wang, X., Srivats, S., Vosoughi, S., … &amp; Wei, J. (2022). Language models are multilingual chain-of-thought reasoners. <em>arXiv preprint arXiv:2210.03057</em>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf11c448b544" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>