<?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 Ria Kulshrestha on Medium]]></title>
        <description><![CDATA[Stories by Ria Kulshrestha on Medium]]></description>
        <link>https://medium.com/@ria-kulshrestha?source=rss-406aa3cbd38e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fi1_Zj3QBbXTB3_B7kEv-w.png</url>
            <title>Stories by Ria Kulshrestha on Medium</title>
            <link>https://medium.com/@ria-kulshrestha?source=rss-406aa3cbd38e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 11:59:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ria-kulshrestha/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[Tree of Thought]]></title>
            <link>https://medium.com/data-science-collective/tree-of-thought-2d61b92ead38?source=rss-406aa3cbd38e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d61b92ead38</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ria Kulshrestha]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 18:52:03 GMT</pubDate>
            <atom:updated>2025-12-10T09:32:15.692Z</atom:updated>
            <content:encoded><![CDATA[<h4>Taking Chain of Thought a step further</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8lNI_zfrb3yUppdxW56LA.png" /></figure><p>While Language Models (LMs) have demonstrated an ever-wider range of reasoning capabilities, from mathematical problems to symbolic manipulation, their underlying mechanism remains a simple, left-to-right, token-level decision process. In <a href="https://medium.com/data-science-collective/so-you-think-you-can-prompt-b3384664bafc">So You Think You Can Prompt</a>(explores Chain of Thought) and <a href="https://medium.com/data-science-collective/beyond-chain-of-thought-b14c0001eb80">Beyond Chain of Thought</a>, we explored two such left-to-right, token-level processing techniques. In this article we explore the problems with such techniques and Tree of Thought, a paradigm that explores the problem space as a tree instead of exploring just a single branch.</p><h4>Table of Content</h4><ol><li>The Problem: LLMs as “System 1” Thinkers</li><li>Tree of Thoughts (ToT) Paradigm</li><li>Core Components of ToT</li><li>Experiments Results</li><li>Pros &amp; Cons</li><li>References And Acronyms Used</li></ol><h3><strong>The Problem: LLMs as “System 1” Thinkers</strong></h3><p>The literature on human cognition suggests that people have two modes in which they engage with decisions — a fast, automatic, unconscious mode (“System 1”) and a slow, deliberate, conscious mode (“System 2”).</p><p>These two modes have previously been connected to a variety of mathematical models used in machine learning. The simple associative token-level choices of LLMs are also reminiscent of “System 1”, and thus might benefit from augmentation by a more deliberate “System 2” planning process that (1) maintains and explores diverse alternatives for current choices instead of just picking one, and (2) evaluates its current status and actively looks ahead or backtracks to make more global decisions, or in simple words — searching a tree of possible paths to the solution of a problem.</p><h3><strong>Tree of Thoughts (ToT) Paradigm</strong></h3><p>This led to the proposition of the <strong>Tree of Thoughts (ToT)</strong> paradigm, which enables LLMs to navigate and explore multiple reasoning paths. ToT fundamentally frames any complex task as a search through a combinatorial problem space, maintaining a tree where each ‘thought’ serves as a coherent intermediate step toward a solution. This structure allows the model to self-evaluate its progress and systematically explore the search space with lookahead and backtracking.</p><p>ToT frames any problem as a search over a tree, where each node is a state s = [x, z1…i ] representing a partial solution with the input and the sequence of thoughts so far. A specific instantiation of ToT involves answering four questions:</p><ol><li><a href="#7d24">How to decompose the intermediate process into thought steps?</a></li><li>How to generate potential thoughts from each state?</li><li>How to heuristically evaluate states?</li><li>What search algorithm to use?</li></ol><h3><strong>Core Components of ToT</strong></h3><p>A specific ToT implementation is defined by four operational components:</p><h4>1. Thought decomposition:</h4><p>Defining how the process is broken down into discrete intermediate thought steps.</p><h4>2. Thought generator:</h4><p>Strategies for producing <em>k</em> candidate thoughts from a current state. Two strategies used in the paper are:</p><ol><li><strong>Sample</strong>: independent and identically distributed (i.i.d.) thoughts from a CoT prompt. This works better when the thought space is rich (e.g. each thought is a paragraph), and i.i.d. samples lead to diversity.</li><li><strong>Propose: </strong>Generate<strong> </strong>thoughts sequentially using a “propose prompt” (Game of 24, Figure 2; Crosswords, Figure 6). This works better when the thought space is more constrained (e.g. each thought is just a word or a line), so proposing different thoughts in the same context avoids duplication.</li></ol><h4>3. State Evaluator:</h4><p>Heuristically assessing the progress of states to determine which states to keep exploring and in which order. We consider two strategies to evaluate states either independently or together:</p><ol><li><strong>Value</strong>: A value prompt reasons about the state to generate a scalar value (e.g. 1–10) or a classification (e.g. sure/likely/impossible) that could be heuristically turned into a value. <em>Such valuations do not need to be perfect, and only need to be approximately helpful for decision making.</em></li><li><strong>Vote</strong>: A “good” state is voted out based on deliberately comparing different states in a vote prompt. When problem success is harder to directly value (e.g. passage coherency), it is easier to compare different partial solutions and vote for the most promising one.</li></ol><h4>4.Search Algorithm:</h4><p>The chosen method for systematically navigating the tree.</p><ol><li><strong>Breadth-first search (BFS)</strong> maintains a set of the <em>b</em> most promising states per step.</li><li><strong>Depth-first search (DFS)</strong> explores the most promising state first, until the final output is reached, or the state evaluator deems it impossible to solve the problem from the current state. In the latter case, the subtree from s is pruned to trade exploration for exploitation.</li></ol><p>In both cases, DFS backtracks to the parent state of <strong><em>s</em></strong> to continue exploration.</p><h3>Experiments Results</h3><p>The following experiments were done by the authors to compare the performance of Tree of Thought against other prompt techniques.</p><h4>Game of 24</h4><p>Game of 24 is a mathematical reasoning challenge, where the goal is to use 4 numbers and basic arithmetic operations (+-*/) to obtain 24.</p><p><strong>Baseline Setup:</strong> For the standard <em>input-output (IO)</em> prompt, 5 in-context examples were added. For <em>chain-of-thought (CoT)</em> prompting, each input-output pair was augmented with 3 intermediate equations, each operating on two remaining numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZfiWUR8rRdvQp-cgPng3LA.png" /></figure><p>In the ToT setup,</p><ul><li><strong>Thought Decomposition + Generator:</strong> at each tree node, the remaining numbers are extracted and the LM is prompted to propose possible next steps. The same “propose prompt” is utilized for all three thought steps, despite having only one example with four input numbers.</li><li><strong>Search Algorithm:</strong> A breadth-first search (BFS) is performed, where at each step, the best 5 candidates are retained.</li><li><strong>State evaluator: </strong>The LM is prompted to evaluate each thought candidate as “sure/maybe/impossible” with respect to reaching 24. Values are sampled 3 times for each thought.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahs1ZTGL-P-l5LkNektTZA.png" /></figure><p><strong>Result:</strong> On the Game of 24 mathematical challenge, ToT’s impact was dramatic. The baseline I/O, CoT and CoT-SC<em>[Chain of Thought + Self Consistency]</em> methods yielded meager success rates of 7.3%, 4.0% and 9.0% respectively. In sharp contrast, ToT achieved a 45% success rate with a narrow breadth (b=1) and a compelling <strong>74%</strong> with b=5. This demonstrates a decisive superiority over direct left-to-right decoding as around 60% of CoT samples already failed the task after generating the first step, or equivalently, the first three words (e.g. “4 + 9”).</p><h4>Creative Writing</h4><p>The input is 4 random sentences and the output should be a coherent passage with 4 paragraphs that end in the 4 input sentences respectively.</p><p><strong>Evaluation Process:</strong> Evaluating passage coherency in two ways: using a GPT-4 zero-shot prompt to provide a 1–10 scalar score, or using human judgments to compare pairs of outputs from different methods. We employ a subset of the authors in a blind study to compare the coherency of CoT vs. ToT generated passage pairs, where the order of passages is randomly flipped over 100 inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTvzKoXP0blG08B8lWbeCQ.png" /><figcaption>ToT setup for Creative writing</figcaption></figure><p><strong>Setup:</strong> Both IO and CoT prompts are zero-shot. IO prompts the LM to directly generate a coherent passage given input constraints, CoT prompts the LM to first make a brief plan then write the passage, i.e. the plan serves as the intermediate thought step.<br>ToT with depth 2 (and only 1 intermediate thought step) — the LM first generates k = 5 plans and votes for the best one (Figure 4), then similarly generate k = 5 passages based on the best plan then vote for the best one. Here the breadth limit b = 1, as only one choice is kept per step. A simple zero-shot vote prompt (“analyze choices below, then conclude which is most promising for the instruction”) is used to sample 5 votes at both steps.</p><p>A third approach for thought generation: iterative refinement was also used for thought generation in IO and ToT where new thoughts were refined from old thoughts instead of i.i.d. or sequentially generation.</p><p><strong>Results: </strong>Figure below shows average GPT-4 scores across 100 tasks, where ToT (7.56) is deemed to generate more coherent passages than IO (6.19) and CoT (6.93) on average. The authors do acknowledge that such an evaluation might be noisy. The findings, however, are also confirmed by the human evaluations. In 41 cases ToT was superior to CoT. If you look at the second part of the results on the left, where iterative refine was used, it was more effective and improved coherency scores for both IO and ToT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQPfXfnvHOyMOq9FpHMgbg.png" /></figure><h4>Mini Crosswords</h4><p>We provide 5 example input-output pairs in the IO prompt, and in the CoT prompt additionally include intermediate words in the order. We run each prompt for 10 samples and average the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnSaAyd1q8qOGVW9FqQmgg.png" /><figcaption>ToT mini crossword setup</figcaption></figure><p>ToT: We leverage a depth-first search that keeps exploring the most promising subsequent word clue until the state is no longer promising, then backtrack to the parent state to explore alternative thoughts. . For thought generation, at each state we translate all existing thoughts into letter constraints for remaining clues and prompt a proposal prompt 5 times to come up with candidates for where and what to fill in the next word. We also prompt the LM to give a confidence level for different thoughts, and aggregate these across proposals to obtain a sorted list of next thoughts to explore. For state evaluations, we similarly translate each state into letter constraints for remaining clues, then evaluate for each clue if it is possible to fill given the constraints. If any remaining clue is deemed “impossible” to fill in, then the exploration of the state’s subtree is pruned and DFS backtracks to its parent to explore the next promising thought.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*EdQN_3Y0FQn3ddKeKVcnog.png" /></figure><p><strong>Result</strong>: Both I/O and CoT failed to exceed 16% word-level success, ToT <em>tripled</em> performance, achieving a 60% word-level success rate and solving 4 out of 20 games.</p><h3>Pros</h3><ol><li><strong>Generality</strong>: ToT encompasses existing methods (I/O, CoT) as special cases. (i.e. trees of limited depth and breadth).</li><li><strong>Modularity &amp; Adaptability:</strong> Allows for independent variation of the base LM, thought procedures, and search algorithms to fit diverse constraints.</li><li><strong>Convenience:</strong> Requires no extra training, functioning purely on top of a pre-trained model.</li><li><strong>Interpretability:</strong> Significantly enhances the transparency of model decision-making.</li></ol><h3>Cons</h3><ol><li><strong>Computational Cost:</strong> Deliberate search necessitates substantially more resources than standard decoding.</li><li><strong>Necessity:</strong> May be an unnecessary complexity for tasks that current LLMs already solve effectively.</li><li><strong>Scope:</strong> Initial studies have been restricted to a limited set of relatively simple tasks.</li></ol><h3>References And Acronyms Used</h3><ul><li><a href="https://arxiv.org/pdf/2305.10601">Tree of Thoughts: Deliberate Problem Solving with Large Language Models by Shunyu Yao, Dian Yu and co.</a></li><li>Github repo: <a href="https://github.com/princeton-nlp/tree-of-thought-llm">https://github.com/princeton-nlp/tree-of-thought-llm</a></li><li>CoT = <a href="https://medium.com/data-science-collective/so-you-think-you-can-prompt-b3384664bafc">Chain of Thought</a></li><li>Cot-SC = <a href="https://medium.com/data-science-collective/beyond-chain-of-thought-b14c0001eb80">Chain of Thought with Self Consistency</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d61b92ead38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/tree-of-thought-2d61b92ead38">Tree of Thought</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Chain of Thought]]></title>
            <link>https://medium.com/data-science-collective/beyond-chain-of-thought-b14c0001eb80?source=rss-406aa3cbd38e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b14c0001eb80</guid>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ria Kulshrestha]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 01:41:43 GMT</pubDate>
            <atom:updated>2025-07-25T11:11:55.878Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring Self Consistency to increase LLM’s robustness</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ag3gl9K8FvHdY3O5" /><figcaption>Photo by <a href="https://unsplash.com/@solenfeyissa?utm_source=medium&amp;utm_medium=referral">Solen Feyissa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After learning about Chain of Thought, the prompts got better but it still doesn’t work for everything. So where do we go from here?</p><p>If you remember in <a href="https://medium.com/p/b3384664bafc">my previous article</a>, we discussed one flaw of LLMs — they are inconsistent. Just because we solved a problem with one prompt, it doesn’t guarantee that a slightly different variant of the prompt will also return the same result. This makes them difficult to rely on and one must verify the answers they give to some degree. But can this inconsistency be used to improve our confidence (and in general the robustness) in LLMs’ responses?</p><h3>Self Consistency</h3><blockquote>Self-consistency leverages the intuition that complex reasoning tasks typically admit multiple reasoning paths that reach a correct answer. The more that deliberate thinking and analysis is required for a problem, the greater the diversity of reasoning paths that can recover the answer.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzMnEG4cBc2Kpl7bhw6NBw.png" /><figcaption>Self consistency explained. Src: the paper.</figcaption></figure><p>What the authors of <a href="https://arxiv.org/pdf/2203.11171">this paper</a> are trying to say here is that if you arrive at the same answer by following multiple reasoning paths, the odds of that answer being correct is higher than the answers which it arrived at only once. Such an approach is analogous to the human experience that if multiple different ways of thinking lead to the same answer, one has greater confidence that the final answer is correct.</p><p>Think of a class of 10 students, 7 of the students arrive at the same answer while the 3 have 3 different answers. The odds of the common answer being correct is statistically higher than any of the 3 other answers. Is it guaranteed that the common answer is the correct answer? NO. In a similar way, if LLMs arrive at the same answer by multiple reasoning paths, the odds of that being the correct answer is higher, but correctness is still not guaranteed.</p><p>Since language models are not perfect reasoners (like the students in our hypothetical class), the model might also produce an incorrect reasoning path or make a mistake in one of the reasoning steps, but such solutions are <strong><em>less likely to arrive at the same answer.</em></strong> That is, the paper hypothesizes that correct reasoning processes, even if they are diverse, tend to have greater agreement in their final answer than incorrect processes.</p><h3>Steps for Self Consistency</h3><p>Instead of greedily decoding the optimal reasoning path as traditional LLMs do, the paper proposes a “<em>sample-and-marginalize</em>” decoding procedure. They first sample from the language model’s decoder to generate a diverse set of reasoning paths.</p><p>Then they generate an answer for each reasoning path, hoping some reasoning path might lead to a different final answer. (Getting the same answer from all paths might only happen for simple problems — for which you might not need self consistency in the first place to achieve good performance.)</p><p>Lastly, they determine the optimal answer by “<em>marginalising”</em> out the sampled reasoning paths to find the most consistent answer in the final answer set.</p><p>In layman terms, prompt the LLM a few times so that it generates different reasoning paths for the same prompt. Collect all the answers. Return the most frequently returned answer.</p><p>One should note that self-consistency can be applied only to problems where the final answer is from a fixed answer set, but in principle this approach can be extended to open-text generation problems if a good metric of consistency can be defined between multiple generations, e.g., whether two answers agree or contradict each other.</p><h3>How to Generate Multiple Reasoning Paths?</h3><p>So it sounds convincing, how do I try this out for my problem? In the paper the authors performed all experiments in the few-shot setting, without training or fine-tuning the language models. They generated various reasoning paths by applying <a href="https://www.hopsworks.ai/dictionary/llm-temperature">temperature</a> (aka creativity parameter) sampling and truncated the top k tokens. The truncation step is optional and wasn’t used in all cases.</p><p>Some particulars they mentioned, in case you want to recreate the results. Though things get outdated in a blink of an eye, so it might be worthwhile to experiment a bit.</p><blockquote>For UL2–20B and LaMDA-137B we applied temperature sampling with T = 0.5 and truncated at the top-k (k = 40) tokens with the highest probability, for PaLM-540B we applied T = 0.7, k = 40, and for GPT-3 we use T = 0.7 without top-k truncation.</blockquote><h3>Experiments Results</h3><h4>Arithmetic Reasoning</h4><p>The results are shown in Table 2. 7. Self-consistency improves the arithmetic reasoning performance over all four language models significantly over chain-of-thought prompting. More surprisingly, the gains become more significant when the language model’s scale increases, e.g., we see +3%-6% absolute accuracy improvement over UL2–20B but +9%-23% for LaMDA137B and GPT-3.</p><h4>Commonsense and Symbolic Reasoning</h4><p>Self-consistency yielded large gains across all four language models, and obtained SoTA results on 5 out of 6 tasks. For symbolic reasoning, they tested the out-of-distribution (OOD) setting where the input prompt contains examples 4-letters and 4-flips (this setting is more challenging as PaLM-540B or GPT-3 can already achieve perfect in-distribution accuracy). In this challenging OOD setting, the gain of self-consistency is still quite significant compared to CoT-prompting with sufficient model sizes. The results show that sampling a higher number (e.g., 40) of reasoning paths leads to a consistently better performance.</p><h3>Comparison to Other Existing Approaches</h3><h4>Sample-and-Rank</h4><p>One commonly used approach to improve generation quality is sample-and-rank, where multiple sequences are sampled from the decoder and then ranked according to each sequence’s log probability. While sample-and-rank does improve the accuracy with additionally sampled sequences and ranking, the gain is much smaller compared to self-consistency.</p><h4>Beam Search</h4><p>For a fair comparison we report the accuracy under the same number of beams and reasoning paths. On both tasks self-consistency outperforms beam search significantly. Note self-consistency can also adopt beam search to decode each reasoning path, but its performance is worse compared to self-consistency with sampling.</p><h4>Ensemble-based Approaches</h4><p>Compared to self-consistency, existing ensemble-based approaches achieve a much smaller gain. In addition, note that self-consistency is different from a typical model-ensemble approach, where multiple models are trained and their outputs are aggregated. Self-consistency acts more like a “self-ensemble” on top of a single language model.</p><h3>Pros of Self-consistency</h3><ul><li>Self-consistency is entirely unsupervised.</li><li>It works off-the-shelf with pre-trained language models.</li><li>It requires no additional human annotation.</li><li>It avoids any additional training, auxiliary models or fine-tuning.</li><li>Self-consistency also differs from a typical ensemble approach where multiple models are trained and the outputs from each model are aggregated, it acts more like a “self-ensemble” that works on top of a single language model.</li></ul><h3>Cons of Self-consistency</h3><ul><li>It incurs more computation cost.</li><li>Still doesn’t guarantee a correct answer.</li></ul><h3>References</h3><ul><li><a href="https://arxiv.org/pdf/2203.11171">https://arxiv.org/pdf/2203.11171</a>-- The paper</li><li><a href="https://learnprompting.org/docs/intermediate/self_consistency?srsltid=AfmBOooGcy5rxs0a7Yea4mDiPTvLquCCiQ9IWHK8XkwPLCzEi0KTiH4L">https://learnprompting.org/docs/intermediate/self_consistency?srsltid=AfmBOooGcy5rxs0a7Yea4mDiPTvLquCCiQ9IWHK8XkwPLCzEi0KTiH4L</a></li><li><a href="https://www.promptingguide.ai/techniques/consistency">https://www.promptingguide.ai/techniques/consistency</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b14c0001eb80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/beyond-chain-of-thought-b14c0001eb80">Beyond Chain of Thought</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[So you think you can prompt?]]></title>
            <link>https://medium.com/data-science-collective/so-you-think-you-can-prompt-b3384664bafc?source=rss-406aa3cbd38e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3384664bafc</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[chain-of-thought]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Ria Kulshrestha]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 23:59:16 GMT</pubDate>
            <atom:updated>2025-03-18T20:44:09.939Z</atom:updated>
            <content:encoded><![CDATA[<h4>Looking at research on prompting (mostly Chain of Thought).</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ryi21JSXmAmk43WM" /><figcaption>Photo by <a href="https://unsplash.com/@googledeepmind?utm_source=medium&amp;utm_medium=referral">Google DeepMind</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The rise of Generative AI (Gen-AI) and its chatbots has undeniably taken the world by storm. It’s almost Luddite-like to <em>not</em> be aware of their impact. I certainly feel a bit like one writing this article because are still people trying to solve problems themselves and looking for answers on the web? Hopefully I am not in the minority. Luddite or not, the advances are truly fascinating and here in my humble attempt to keep up with things, I am sharing my notes on my deep dives in the world of prompting.</p><h3>Prompts: Origin</h3><p>Historically, ML models required inputs in a fixed format and therefore were inaccessible to a vast majority of people and were unable to infiltrate our day to day chores. However, with the increasing capabilities of large language models (LLMs), <strong>in-context learning</strong> (ICL) has emerged as a new paradigm for natural language processing (NLP). ICL allows LLMs to make predictions based on contexts — usually provided through a prompt — that enable users to interact with them using natural language and apply them to everyday problems.</p><p>A “prompting-only” approach became viral because</p><ul><li>It doesn’t require a large training dataset to perform a task successfully.</li><li>A single model checkpoint can perform many tasks without loss of generality, making it easier to provide it as a service (think of all the bots) to end-users.</li><li>It eliminates fixed input formats, making it very easy to use without a steep learning curve (unlike previous non-NLP-based models).</li></ul><p>Now that natural language, prompt-based models are ubiquitous in user product journeys and our lives, it is imperative to learn more about them. Understanding their full potential, limitations and biases allows us to use them responsibly and benefit from them without falling prey to the misinformation (worst case) or looking like an idiot saying the wrong things confidently (umm least worst case).</p><h3>How much difference can the quality of a prompt make?</h3><p>First things first: not all prompts are created equal. The “garbage in, garbage out” rule still applies. The quality of your prompt directly determines the quality of the answer you get and in mathematical cases whether you solved the problem or not.</p><p>In short, a prompt makes a HUGE difference! See <a href="https://arxiv.org/html/2406.10248v2">this research paper</a> for in-depth analysis. This dependency on prompt quality leads to a robustness problem. See Table 1 (in the paper) for a quick overview.</p><blockquote>There is a significant gap between the worst performance (lower bound) and best performance (upper bound) for all models. For instance, the worst and best performance of Llama-2–70B-chat are 0.094 and 0.549, respectively, indicating a difference of 0.455. This suggests that the current LLMs’ ability to follow instructions is not robust enough. <strong>Even instructions with identical semantics and fluent expressions could lead models like Llama2–70B-chat to plummet from a level comparable to GPT4 (0.5 indicates equivalence to the reference model) to far below the average level (0.292)</strong>.</blockquote><p>^ Quote from the above mentioned paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/0*0zPnFhOolH1c1UwW.png" /><figcaption><a href="https://xkcd.com/1838/">Image from xkcd comics</a>.</figcaption></figure><h3>Shot-Based Prompting</h3><p>This is a quick review of shot prompting, where you provide the context along with some examples of similar solved problems. The number of examples provided are shots (I am not sure how this term came about to be).</p><h4>Zero-Shot Prompting</h4><p>Only the problem statement is provided; no examples are given in the prompt.</p><p><strong><em>Example Prompt:</em></strong> How many ‘r’ are there in the word “strawberry”?</p><h4>Single-Shot Prompting</h4><p>A single example is given along with the problem statement.</p><p><strong><em>Example Prompt:</em></strong> <br>Question: How many ‘e’ are there in the word “blueberry”?<br>Answer: There are 2 ‘e’s in “blueberry”.<br>How many ‘r’ are there in the word “strawberry”?</p><h4>Few-Shot Prompting</h4><p>An LLM receives in-context exemplars of input–output pairs before outputting a prediction for a test-time example.</p><p><strong><em>Example Prompt:</em></strong> <br>Question: How many ‘e’ are there in the word “blueberry”?<br>Answer: There are 2 ‘e’s in “blueberry”.<br>Question: How many ‘p’ are there in the word “pineapple”?<br>Answer: There are 3 ‘p’s in “pineapple”.<br>How many ‘r’ are there in the word “strawberry”?</p><h3>Chain of Thought Prompting</h3><p>A chain of thought is a series of intermediate natural language reasoning steps that lead to the final output. In chain-of-thought (CoT) prompting, we use few-shot prompting and augment each exemplar with a chain of thought for an associated answer. The prompt consists of triples: <em>&lt;input, chain of thought, output&gt;</em>.</p><p><strong><em>Example Prompt:<br></em>Question:</strong> How many ‘e’ are there in the word “blueberry”? <br><strong>Chain of Thought:</strong> To find the number of ‘e’s in “blueberry”, I need to examine each letter of the word. Going through the word, I see an ‘e’ at the beginning and another ‘e’ near the end. That makes a total of two ‘e’s. <br><strong>Answer:</strong> There are 2 ‘e’s in “blueberry”.</p><p><strong>Question:</strong> How many ‘p’ are there in the word “pineapple”? <br><strong>Chain of Thought:</strong> Let’s look at each letter in “pineapple”. I see a ‘p’ at the beginning, another two ‘p’s in the middle. So, there are three ‘p’s. <br><strong>Answer:</strong> There are 3 ‘p’s in “pineapple”.</p><p><strong>Question:</strong> How many ‘r’ are there in the word “strawberry”?</p><p>CoT works better than few-shot prompting alone because traditional few-shot prompting methods (used in <a href="https://arxiv.org/pdf/2005.14165">Brown et al. (2020)</a>) struggle on tasks that require reasoning abilities and often do not improve significantly with increasing language model scale.</p><h4>Pros <strong>of Chain-of-Thought Prompting</strong>:</h4><p>CoT prompting has several attractive properties as an approach for facilitating reasoning in language models.</p><ol><li><strong>Decomposition: </strong>CoT, in principle, allows models to decompose multi-step problems into intermediate steps, allocating more computation to complex problems.</li><li><strong>Interpretability: </strong>A CoT provides an interpretable window into the model’s behaviour, suggesting how it arrived at a particular answer and providing opportunities to debug incorrect reasoning paths (although fully characterising a model’s computations that support an answer remains an open question).</li><li><strong>Versatility: </strong>CoT reasoning can be used for tasks such as math word problems, common sense reasoning, and symbolic manipulation. It is potentially applicable (at least in principle) to any task that humans can solve via language.</li><li><strong>Ease of Implementation: </strong>CoT reasoning can be easily elicited in sufficiently large off-the-shelf language models simply by including examples of CoT sequences into the exemplars of few-shot prompting.</li></ol><h3>Results <strong>of CoT Prompting</strong></h3><p><a href="https://arxiv.org/pdf/2201.11903">This paper</a> qualitatively explores CoT prompting across various baseline datasets and found the following results:</p><ol><li>CoT prompting <strong>doesn’t positively impact performance for small models</strong>, and it only yields performance gains when used with models of ∼100B parameters. Smaller scale models produced fluent but illogical chains of thought, leading to lower performance than standard prompting. <em>(Note: the paper this was based on was published before Deep-seek so this may no lobger be the case)</em></li><li>It has <strong>larger performance gains for more-complicated problems</strong>. For instance, for GSM8K (the dataset with the lowest baseline performance), performance more than doubled for the largest GPT and PaLM models. On the other hand, for SingleOp, the easiest subset of MAWPS which only requires a single step to solve, performance improvements were either negative or very small.</li><li>Chain-of-thought prompting via GPT-3 175B and PaLM 540B compares favourably to prior state of the art, which typically fine tunes a task-specific model on a labeled training dataset.</li></ol><h3>Robustness of Chain of Thought</h3><p>CoT is more robust than few-shot prompts. While there is variance among different chain of thought annotations, all sets of chain of thought prompts outperform the standard baseline by a large margin. This implies that successful use of chain of thought does not depend on a particular linguistic style. CoT prompting for arithmetic reasoning is robust to different exemplar orders and varying numbers of exemplars.</p><h4>Different number of exemplars</h4><p>Gains from chain-of-thought prompting generally still held when there was a varying number of few-shot exemplars. Increasing the number of exemplars in standard prompting did not lead to significant gains (e.g., increasing from 8 to 16 exemplars did not improve the performance of standard prompting enough to catch up with chain-of-thought prompting). This shows that CoT is more robust than standard few shot prompting.</p><h3>Does CoT work on other types of problems?</h3><h4>Common sense Reasoning</h4><p>So far, most of the results are based on mathematical problem datasets. The language-based nature of chain of thought actually makes it applicable to a broad class of common sense reasoning problems.</p><p>Similar to the mathematical problems, for all tasks, scaling up model size improved the performance of standard prompting; CoT prompting led to further gains even when the tasks required a range of common-sense abilities (though the improvement was minimal).</p><h4>Symbolic Reasoning</h4><p>To measure improvements at symbolic tasks, the paper tests various models with CoT prompts at two toy tasks:</p><ol><li><strong>Last-letter concatenation:</strong> This task asks the model to concatenate the last letters of words in a name (e.g., “Amy Brown” → “yn”).</li><li><strong>Coin flip:</strong> This task asks the model to answer whether a coin is still heads up after people either flip or don’t flip the coin (e.g., “A coin is heads up. Phoebe flips the coin. Osvaldo does not flip the coin. Is the coin still heads up?” → “no”).</li></ol><p>These in-domain evaluations are “toy tasks” in the sense that perfect solution structures are already provided by the chains of thought in the few-shot exemplars; all the model has to do is repeat the same steps with the new symbols in the test-time example.</p><p>However, small models still fail — the ability to perform abstract manipulations on unseen symbols for these tasks only arises at the scale of 100B model parameters.</p><h3>Limitations of CoT</h3><p>CoT is not a universal solution and comes with a set of limitations.</p><ul><li><strong>Annotation Cost: </strong>While the cost of manually augmenting exemplars with chains of thought is minimal in the few-shot setting, such <strong>annotation costs could be prohibitive for fine tuning</strong> (though this could potentially be surmounted with synthetic data generation, or zero-shot generalisation).</li><li><strong>Computational Cost: </strong>The emergence of chain-of-thought reasoning <strong>only at large model scales makes it costly</strong> to serve in real-world applications.</li><li><strong>Reasoning Errors: </strong>There is <strong>no guarantee of correct reasoning paths</strong>, which can lead to both correct and incorrect answers.</li><li><strong>“Reasoning” Question: </strong>Although chain of thought emulates the thought processes of human reasoners, this does not answer whether the neural network is actually “reasoning”.</li><li><strong>Model Dependence: </strong>If the same prompt is used for 3 different models, we don’t get the same improvement across all 3 models. The fact that gains don’t transfer perfectly among models is a limitation.</li><li><strong>Model Specificity: </strong>Further work is needed to investigate how different pre-training datasets and model architectures affect the performance gain from chain-of-thought prompting.</li></ul><h3><strong>Why does the Chain of Thought work?</strong></h3><p>The observed benefits of using CoT prompting raises the natural question of whether the same performance improvements can be conferred via other types of prompting.</p><p>The paper tests three variations to see if CoT is the cause of improved performance.</p><h4>Equation-Only Prompting</h4><p>Instead of the final answer, the model was asked to output only the final equation. Equation-only prompting doesn’t help much for questions that are too challenging to directly translate into an equation without the natural language reasoning steps in the chain of thought. However, for datasets of one-step or two-step problems, we find that equation only prompting does improve performance, since the equation can be easily derived from the question.</p><h4>Variable Compute Only</h4><p>Another intuition is that chain of thought allows the model to spend more computation (i.e., intermediate tokens) on harder problems. To isolate the effect of variable computation from chain-of-thought reasoning, the paper tests a configuration where the model is prompted to output only a sequence of dots (. . .) equal to the number of characters in the equation needed to solve the problem. This variant performs about the same as the baseline, suggesting that variable computation by itself is not the reason for the success of CoT prompting and that there appears to be utility from expressing intermediate steps via natural language.</p><h4>Chain of thought after answer</h4><p>Another potential benefit of chain-of-thought prompting (as compared to. vanilla few-shot prompting) could simply be that such prompts allow the model to better access relevant knowledge acquired during pre-training. Therefore, the paper tests an alternative configuration where the CoT prompt is only given after the answer, isolating whether the model actually depends on the produced chain of thought to give the final answer. This variant performs about the same as the baseline, suggesting that the sequential reasoning embodied in the chain of thought is useful for reasons beyond just activating knowledge.</p><h3>Conclusion</h3><p>Prompt engineering is a rapidly evolving field and its power is undeniable. While techniques like chain-of-thought prompting offer significant improvements in LLM performance, they are not a panacea. Understanding both the strengths and limitations of these methods is crucial for responsible and effective application of Gen-AI. As models continue to evolve, so too must our understanding of how to best leverage their capabilities. As we increasingly rely on LLMs in various aspects of our lives, it’s essential to be aware of their potential biases and limitations. The journey of prompt optimisation is just beginning, and continuous learning and experimentation are key to unlocking the full potential of LLMs.</p><h3>References/Future reads</h3><ul><li><a href="https://arxiv.org/pdf/2201.11903">The CoT paper</a>, also linked above.</li><li>How much difference a prompt makes, read <a href="https://arxiv.org/html/2406.10248v2">this</a>.</li><li>Learn more about transformers — that give LLMs its superpowers, read <a href="https://medium.com/towards-data-science/transformers-89034557de14">here</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3384664bafc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/so-you-think-you-can-prompt-b3384664bafc">So you think you can prompt?</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[O(h) Auth: Part 1]]></title>
            <link>https://ria-kulshrestha.medium.com/o-h-auth-part-1-8e7a540997aa?source=rss-406aa3cbd38e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e7a540997aa</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Ria Kulshrestha]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 10:32:29 GMT</pubDate>
            <atom:updated>2023-04-05T10:32:29.096Z</atom:updated>
            <content:encoded><![CDATA[<h3>O(h) Auth</h3><h4>Understanding the most widely used security protocol</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0AQzDCGsaNltA3ZA" /><figcaption>Photo by <a href="https://unsplash.com/@gneri1713?utm_source=medium&amp;utm_medium=referral">Gina Neri</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is OAuth?</h3><p>OAuth (Open Authorisation) is an open standard (basically guidelines) for <strong>authorisation</strong> (not authentication). To know the difference between the two, read more <a href="https://medium.com/@ria-kulshrestha/intro-to-privacy-preserving-ml-4d96accbf1a1">here</a>.</p><p>It is commonly used as a way for access delegation — internet users grant websites or applications access to their information but without giving them the passwords.</p><h3>What do OAuth guidelines say?</h3><p>OAuth recommends a safe and secure way to allow <strong><em>access</em></strong> to a certain resource/information without actually sharing it. Think of your resource as a painting in a museum, anyone with a ticket can look at it, they can look at it as many times as they want in a single visit, they can even take a picture of it. But they can’t take the painting home, they can’t enter again without a new ticket, and while anyone can get a ticket it is you who decides to whom you want to sell tickets and which sections of the museum are accessible.</p><p>The ticket is just an example of how access can be controlled. The actions that are allowed can vary. Maybe phones aren’t allowed, so no pictures can be taken of the paintings.</p><p>OAuth does the same by the means of tokens in the online world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S4pPgHNy9cI7zU-K" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@rm_photography?utm_source=medium&amp;utm_medium=referral">Roth Melinda</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Auth is one tricky pony and usually SWEs don’t try to play around much with it because 99% of the time it can’t be tested locally and if it breaks ALL traffic to your service is affected. It has a notorious reputation in the tech world. So no team will change their auth policies just for fun. And it is not often you get to work on it unless you are in a dedicated team.</p><h3>Basic Components in OAuth</h3><h4>An Example</h4><p>You [<em>Client</em>] are at a hotel reception and trying to check-in to your beautiful room [<em>Resource Server</em>]. The receptionist [<em>Authorization Server</em>] asks for some valid documents for verifying your identity. (<em>Note: This part is Authentication, not Authorisation</em>) Then the receptionist checks the hotel system [ <em>~ Resource Owner</em>] to see if you have a booking with them [<em>Authorisation!!</em>]. If you do, they give you the room keys [<em>Token that give you access to the resource for a fixed amount of time</em>]. Then you use the keys to access your room. Once your stay is over [<em>token is expired</em>], you need to do the whole dance again to get access to the resource. The access was scoped because you could access only your room. But it could be different for hotel employees, who can access multiple rooms with the master key. Another example could be those all inclusive hotels where the colour code of the band determines what privileges you get. Maybe only the bar and no spa access or something like that.</p><p><strong><em>Tl;dr</em></strong> - The resource owner (<em>hotel</em>) was able to delegate access for a certain resource (<em>room</em>) to the client (<em>you</em>). The access was scoped because there were limits to what you can do based on your token.</p><h4>Informal definitions</h4><ul><li><strong><em>Client</em></strong>: Wants access to a certain resource.</li><li><strong><em>Resource Owner:</em></strong> Indirectly/directly owns and controls access to the resource.</li><li><strong><em>Authorisation Server:</em></strong> Checks if the request has valid scopes to access the resources in the request. So scopes can change based on the type of request. Get request will require only read access while an Update request might require read/write access. Usually(almost always) applications have a separate service that performs these checks and aren’t coupled with the application service that contains the business logic.</li><li><strong><em>Scope:</em></strong> Constraints what access a user is privileged to have for a certain resource.</li><li><strong><em>Token: </em></strong>Contains scope and identity information that a client has/wants to use. Obtained through various OAuth grant types.</li></ul><p>There are different types of tokens and <strong>grants</strong> (steps to fetch tokens/how tokens are <strong>granted</strong>) to support different kinds of authorisation flows. These are the most popular ones in a complex flow:</p><ul><li><strong><em>Access tokens:</em></strong> Allows access to a resource for a fixed(short) time. A popular sub type is a bearer token that allows access to whoever has the token (with some extra check for security obviously).</li><li><strong><em>Refresh tokens:</em></strong> If application needs to perform an action in the future, getting an access token is of no use as it will simply expire. You can’t ask for a fresh token from the user right before performing the action, but you can get a refresh token from the user instead during the interaction. Later when you need to perform the action, you can exchange the refresh token for an access one.</li></ul><p>The token choice and how it is obtained depends a lot on the kind of flow we have — is it user initiated, after how long does the service need to perform the action etc.</p><p>In future posts I will break down some popular auth flows we use frequently such as log in, log in with &lt;some third party email account&gt;, machine to machine calls and more.</p><h3>More Resources</h3><ul><li><a href="https://www.fortinet.com/resources/cyberglossary/api-key">API Keys</a></li><li><a href="https://developer.okta.com/blog/2017/06/21/what-the-heck-is-oauth">OAuth</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e7a540997aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Privacy Preserving ML]]></title>
            <link>https://medium.com/analytics-vidhya/intro-to-privacy-preserving-ml-4d96accbf1a1?source=rss-406aa3cbd38e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d96accbf1a1</guid>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ria Kulshrestha]]></dc:creator>
            <pubDate>Fri, 29 Jul 2022 18:31:00 GMT</pubDate>
            <atom:updated>2022-07-29T18:31:00.130Z</atom:updated>
            <content:encoded><![CDATA[<h4>Because privacy is power.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MrED-jIjF06I8Gjz" /><figcaption>Photo by <a href="https://unsplash.com/@californong?utm_source=medium&amp;utm_medium=referral">Nong Vang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Note</h4><p>This article contains my notes from my initial reading about privacy preserving ML for a hackathon project some 2y ago (so doesn’t cover the latest state) and some added context why the topic is relevant and its impact.</p><h3>Introduction</h3><p>Remember in the 90s (or was it 00s?), when the Internet was the latest buzz. Everyone was super excited about building the next big thing on the Internet, and for the longest time nobody paid attention to security. It was a good invention , but once they nailed the security aspect or at least began their attempts, the Internet truly flourished and became the magical, addictive, ubiquitous and larger than life entity we all know, love and sometimes hate! The Internet is now leveraged for services ranging from online banking, stock trading to retailing among many others that would have been unimaginable without security.</p><p>I believe we are in a similar phase with ML. Yes, I’m envious too when an AI draws/writes better content than I do, but there is plenty more possible when we can ensure security and privacy in its development process.</p><h4>Security Vs Privacy — They are NOT the same!</h4><p>Security is about ensuring only authorised people have access to something, while privacy has more to do with who is authorised. You cannot have privacy without security, but the other way around is possible.</p><p>Think of it this way, a hotel room is secure — only people with the key can enter it. But it is not private — any hotel staff with the master key can also enter it, without your knowledge/consent.</p><p>Meanwhile, your house is secure and private because you own the keys and control its distribution as well.</p><p>Let’s try to see what the current ML scenario looks like, are we secure but lack privacy, are we both, or are we neither?</p><h3>ML 2020 — An Analysis</h3><p>Most ML models are trained on a publicly available, unencrypted, and large datasets. The publicly available unencrypted data is accessible to almost anybody, hence it is neither secure nor private.</p><p>The training is followed by fine-tuning on a downstream task, the dataset used here can be public or private, depending on the nature of downstream applications and trainer’s discretion, but it has to be unencrypted. Again, due to the lack of encryption, this is potentially un-secure. At the very least, people who are training the model will have eyes on access to the data.</p><h3>How privacy will benefit ML?</h3><p>An ML model’s performance is majorly driven by the data it is trained on. The availability of different kinds of datasets varies substantially depending on the quality and domain of data one has access to. Most commonly available datasets contain trivial information. These can be very useful to comprehend the basics of ML but can seldom be used directly to solve real problems afflicting real people. Cute dogs and cats can only save the world to an extent.</p><p>If you were to set out to solve a novel and impactful problem, the first hurdle you’ll most likely face is collecting relevant data. Not only you will need to find people/organisations in possession of such data, but also need access to it in an unencrypted state. *legal stuff, better lawyer up!*</p><p>ML is, at its core, a way of pattern matching. In many domains, that can benefit from ML, privacy is of utmost importance. Example: Matching early/rare symptoms with correct diagnosis, improving the quality of lifestyle and health research or improved personalised recommendations not as a marketing strategy but as a way to tackle over-consumerism etc. Getting access to such data is a tedious job and rightfully so, it is indeed very personal and critical information and can easily be misused and abused. This results in a major bottleneck and deters development of many real-life applications from reaping the benefits of the advances in ML. There is little use of those State-Of-The-Art results if we can’t use them to solve real problems.</p><h3>Doing it like the Internet &lt;Ctrl + C &amp;&amp; Ctrl +V&gt;</h3><p>It is evident that this is not the first time in history where concern for privacy is restricting development. Not so long ago, many naysayers believed, the Internet, will never take off and now it is IMPOSSIBLE to imagine a world without it. But it clearly did, you are reading this right now. So can we do the same for ML?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G8_Bc1r_vTWTcrtJ.png" /></figure><p>There are plenty of exchanges happening all over the Internet that deal with sensitive information — passwords, bank details, medical information, photographs, official documents you name it and it is on the internet i.e. potentially available to the prying eyes. But it is not a concern one might expect it to be, things can be available online and still be secure and private, only you and the people you authorise are able to access it. Why can’t we do the same for ML? Less eyes on data would mean exposure of private information only to trusted individuals. One can work with that, or can they?</p><p>Only a few chosen individuals/groups get “eyes-on” access. This could work but this will, intentionally or unintentionally, hamper progress in a totally different way by creating an uneven playing field. Who gets access to data? How to ensure an unbiased distribution? What does the screening process to make such a discussion looks like? It is too much power for a single authority because the last thing we need are more prejudices and barriers to entry to this industry (as if the existing educational/experience/financial/legal requirements aren’t discouraging enough).</p><h3>Privacy Preserving ML</h3><p>Privacy in ML is not completely unheard of, it is not the most lucrative area of research at the moment, but it is starting to grow. It is not in a place to compete with the “State of the Arts” yet, but some great progress have been made. It allows model trainers to develop model while keeping privacy of the data owners in mind. Here are a few ways on how this is done:</p><h3>Remote Execution/Federated Learning</h3><p>There are two parties in an exchange, the model owner and the data owner. Currently, data owner has to trust before sharing the data with the model owner. Once the data is with the model owner you HAVE to, you really can’t do much about it, trust them to do the right thing. What if there is a way to train a model without explicitly handing them the data?</p><p>This is what remote execution allows. Instead of you sharing your data, the model owner shares the model with various data owners. The model trains on the data, possibly in the data owner’s machine and the updated model (think of updated weights after an epoch) is returned to the model owner. This in some way distributes the trust between both data and model owner.</p><p>The data never leaves participants’ device and the ML models of the world can still train on, sounds like a win-win. The data didn’t leave, but some information it held did. This is alright and expected because that is the point of ML model — to extract information from data. The real question is your privacy preserved in this exchange?</p><p>The answer is no. Even if the data is securely with you and the eyes of model owners never really saw it, they can in some rare cases deduce some aspects of the data, even if we make the data owner anonymous. If it sounds far-fetched, read about how <a href="https://www.wired.com/2007/12/why-anonymous-data-sometimes-isnt/">people de-anonymized data by correlating information from two different datasets</a>.<br>The main concern (ignoring the combining of datasets for now) is that if the model learns a new behaviour after training on data of user X, then model owners can conclude that user X’s data must have given that information. Simplified example: Model learns how to identify a new species of dog after User X, then model owners can conclude that User X must own a dog of that species. This may not seem like that big of a con in this example, but the whole point of doing this exercise is to make access, to sensitive and personal data, accessible. Also the user still need to trust the model owner to do the right thing, including not just copying the data in the name of training. And the model owner needs to trust the data owner that they simply won’t copy the model or tamper with it.</p><p>Federated learning is similar to remote execution. In federated learning, the computations are done on remote devices of the data owners and the results are uploaded to the cloud where multiple such results are combined to update the global model. The minor difference I have noticed based on what I have read is that in federated learning, the results will be uploaded whenever available to the cloud, it is similar to pub-sub model in some ways, but in case of remote execution, it is more driven by the model owners, they will reach out to data owners when they need it, and not listen for updates all the time. It kind of makes sense because the data owner is interested in niche data eg: data about cancer and everything and anything medical.</p><h3>Differential Privacy*</h3><p>The above mentioned con can be overcome by using differential privacy in conjunction of remote execution. In differential privacy, in intellectual terms, we create an upper bound on the statistical uniqueness of the dataset aka privacy budget. In layman terms, we add some good old noise. So the model owner can never be 100% sure, in cases such as the one mentioned above, that User X has a dog of the newly learnt species, because it could have been due to noise.</p><p>From what I understand, this budget not only limited to per query but to the overall dataset as well. So you cannot query it multiple times in hopes of recreating the OG set. Example: If you query the same user 10 times and notice that 8/10 times you saw similar results, and hence you can deduce the responses that are noise aren’t. Well this won’t work because of the limit on overall dataset as well. How it ensures that is a topic for a different blog.</p><p>If you are feeling a little sour about the noise being added, as it will reduce the quality of your results, don’t. A little noise in datasets is encouraged because it prevents the ML model from over-fitting. Better generalisation is more likely to give better results on test data, or when we actually use the model in real life applications.</p><p>It is not always practical to be the owner of your own data. For both the data owner and model owner, reaching out to/being reached out by large numbers of users is impractical and honestly annoying. Both parties need to check if they can trust each other and blah blah. Plus how does one de-annonymise it if you are reaching out to individuals?</p><h3>Secure Multi-Party Computation</h3><p>As the name suggests (that’s why you name things) it allows you to <strong><em>securely</em></strong><em> </em>(using encryption) <em>distribute the data across </em><strong><em>multiple parties </em></strong>(better anonymisation) and still allows the <em>training</em><strong><em> computation</em></strong><em> to occur</em>.</p><p>You basically take data and divide it into smaller chunks and encrypt it. Each chunk is “owned” by a different individual who, for obvious reasons cannot decrypt it. When a model owner needs to train their model, it asks all chunk holders to send data to a remote machine, the model is sent to that remote machine and it trains of the data. Or maybe the owner sends the model to train on all share-holders of the chunks. No decryption is required for any step in the process. (This is a rough overview of what happens, actual details of various implementation may vary)</p><p>The individual parties cannot decrypt data on their own. For additional security, the model owners can also encrypt their models. So both, the data owners and model owners can feel lot more comfortable during collaborations. You cannot do all kinds of computations in an encrypted state but most one the basic ones. So the fancy transformers and all that can’t simply adapt to a privacy preserving ML way of training.</p><h3>Conclusion</h3><p>Privacy preserving ML is an exciting area of research and is in its early phase. The solutions we have might not give the results we want to/or expect from ML models at this point, but the area has lot more to offer and will improve tremendously in the years to come. (I’m sure it already has in the 2y I wrote this)</p><h3>Resources</h3><ul><li><a href="https://www.youtube.com/watch?v=4zrU54VIK6k">Privacy Preserving AI (Andrew Trask) | MIT Deep Learning Series</a></li><li><a href="https://blog.openmined.org/">OpenMined Blog</a></li></ul><p>Obviously there are more caveats and intricacies involved here and this is merely a simplified overview of all the sub-topics mention. If you want a follow up on any of them or explore any other concept in this space, please feel free to reach out to me. :D</p><p>*Differential Privacy is a very interesting topic on its own and here I have only covered of what is does on a high level and not how. Most of its claims have a mathematical proof, if you want me to explore it in depth, please reach out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d96accbf1a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/intro-to-privacy-preserving-ml-4d96accbf1a1">Intro to Privacy Preserving ML</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five things you need to do if you are starting out as a software engineer.]]></title>
            <link>https://ria-kulshrestha.medium.com/five-things-you-need-to-do-if-you-are-starting-out-as-a-software-engineer-80bfe562ee21?source=rss-406aa3cbd38e------2</link>
            <guid isPermaLink="false">https://medium.com/p/80bfe562ee21</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mentorship]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[career-advice]]></category>
            <dc:creator><![CDATA[Ria Kulshrestha]]></dc:creator>
            <pubDate>Mon, 30 Nov 2020 16:28:13 GMT</pubDate>
            <atom:updated>2020-11-30T16:28:13.548Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hello, SE world! Start your career the right way.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fwYmMNW1jtispyO2" /><figcaption>Photo by <a href="https://unsplash.com/@max_duz?utm_source=medium&amp;utm_medium=referral">Max Duzij</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>Disclaimer</strong>: I’m not dull enough to suppose that the entirety of software engineering wisdom can be distilled down to five or even ten points. But one needs to start somewhere, right? These action items will help you stay afloat while you figure out your master plan.</blockquote><p>So if you are a college graduate starting out soon, or someone making a career switch, this would be a good place to start. If you have been in this industry for a while, this might not be for you. But don’t leave the page just yet, why don’t you share some of your wisdom in the comments? ;)</p><h3>Action Item #1: Be curious. 🧐</h3><ul><li>Ask questions about the code, system architecture, team culture, team practices, the deployment pipeline, testing support, etc.</li><li>Don’t know whom to ask? I suggest your buddy or mentor. If you don’t have one of those, ask your manager for one of those.</li></ul><h3>Action Item #2: Let the code talk. 👩‍💻</h3><ul><li>Write thoroughly tested code. Everyone prefers a reliable change over a quick one.</li><li>Take time to understand the code and try to reuse code whenever possible and keep it clean. As exciting/challenging writing code from scratch sounds it is not what you should do. If re-usability is possible — even if it requires some refactoring — REUSE it. You want to treat your code base like planet earth and we all know where single use objects (pun intended.) lead to.</li></ul><p><em>Friendly Tip</em>: Do not use this as an excuse and take a week to do something that requires a few hours. Not all tasks assigned to you will be grand enough to pull off this as an excuse.</p><h3>Action Item #3: Do PR Reviews. 📋</h3><ul><li>It is impossible to be involved in everything that is happening, it’s not a single person team for a reason. Coding isn’t the only way to contribute to a products’ development. One of the most valuable way is to review your peers’ PRs. Now this is quite overwhelming for a few of us, *heyyy imposter syndrome, I see you* and you’d be thinking I just got here, how can I tell someone how to something better, but chill out. Start small, it is ok to ask why they did something in a particular way.</li><li>When it comes to your own PR, be as descriptive as possible. Set out the entire context in that description box.</li></ul><h3>Action Item #4: Use 1:1 to learn and grow. 📈</h3><ul><li>Many people believe 1:1s are there for your manager’s benefit and they should run the meeting. But that is the opposite of how it should be. They are there for YOU! Think of them as a default mentoring sessions.</li><li>Use them to make sure to set the expectations right. How do you do that? Well learn what they expect of you in the first place!</li><li>Ask about gaps in your current skill set. Learn how you can increase your impact.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/0*1XQAXcZfxHEL--rf" /><figcaption>Source: <a href="http://www.quickmeme.com/meme/3stmi4">Has monthly 1 on 1 performance review meetings Spends half of the meeting asking about your family and your interests. — Good Guy Boss — quickmeme</a>.</figcaption></figure><h3>Action Item #5: Take ownership. 🏛️</h3><ul><li>As mentioned numerous times before, joining a new team is overwhelming in its own ways and it is only natural to try to learn everything at once. Alas, it is not humanly possible for most of us to do so. A better way to strategize would be to pick a small area and building your expertise around that.</li><li>Next time there is a discussion around any of those areas, make sure to participate and contribute in whatever way possible. Lo and behold, you are an owner of an area.</li></ul><h3>Bonus Tip: Know Git.</h3><p>I have previously written about it, so I will keep it short and link it here.</p><p><a href="https://towardsdatascience.com/git-help-all-2d0bb0c31483">Learning Git in Under 8 minutes!</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*0Q6FEd-nuwdpHdvo.jpg" /></figure><h3>Now What? 🤔</h3><p>Okay, you have been around for a while and already doing all the aforementioned things, what else can you do? What’s next?</p><p>One would think the internet is the go-to place for people like us to share their knowledge but surprisingly so much of it is buried in good old fashioned books.</p><p>Here are a few I recommend:</p><ol><li><a href="https://www.goodreads.com/book/show/26166862-you-had-me-at-hello-world">You Had Me at “Hello, World”: Mentoring Sessions with Industry Leaders at Microsoft, Facebook, Google, Amazon, Zynga and more! by Dona Sarkar</a></li><li><a href="https://www.goodreads.com/book/show/44936.Refactoring?ac=1&amp;from_search=true&amp;qid=gn7YOSEpPd&amp;rank=4">Refactoring: Improving the Design of Existing Code by Martin Fowler</a> — if not the whole thing, read chapter 3. I might make a post about it, so watch out!</li><li><a href="https://www.goodreads.com/book/show/58128.Head_First_Design_Patterns?ac=1&amp;from_search=true&amp;qid=IIn2wIADxY&amp;rank=2">Head First Design Patterns by Eric Freeman</a> — I have read partially and it has been good so far. By partially I meant one chapter.</li></ol><p>Few that are on my reading list:</p><ol><li><a href="https://www.goodreads.com/book/show/4099.The_Pragmatic_Programmer">The Pragmatic Programmer: From Journeyman to Master by Andy Hunt</a></li><li><a href="https://www.goodreads.com/book/show/3735293-clean-code">Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80bfe562ee21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keeping up with the BERTs]]></title>
            <link>https://medium.com/data-science/keeping-up-with-the-berts-5b7beb92766?source=rss-406aa3cbd38e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b7beb92766</guid>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Ria Kulshrestha]]></dc:creator>
            <pubDate>Mon, 26 Oct 2020 16:02:55 GMT</pubDate>
            <atom:updated>2020-11-22T10:46:45.512Z</atom:updated>
            <content:encoded><![CDATA[<h4>The most popular family in NLP town</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CpbAKL6DzAEAKTxW" /><figcaption>Photo by <a href="https://unsplash.com/@leookubo?utm_source=medium&amp;utm_medium=referral">Leonardo Toshiro Okubo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you even slightly follow the NLP world, or even the ML news you have most likely come across Google’s BERT model or one of its relatives. If you haven’t and still somehow have stumbled across this article, let me have the honor of introducing you to BERT — the powerful NLP beast.</p><h3>What is BERT?</h3><p>BERT stands for <strong><em>B</em></strong><em>idirectional </em><strong><em>E</em></strong><em>ncoder </em><strong><em>R</em></strong><em>epresentations from </em><strong><em>T</em></strong><em>ransformers</em> and is a language representation model by Google. It uses two steps, pre-training and fine-tuning, to create state-of-the-art models for a wide range of tasks.</p><p>Its distinctive feature is the unified architecture across different downstream tasks — what these are, we will discuss soon. That means that the same pre-trained model can be fine-tuned for a variety of final tasks that might not be similar to the task model was trained on and give close to state-of-the-art results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGg2gOPc-gzfvDofWDIbqQ.png" /><figcaption>BERT consists of two steps. Source: <a href="https://arxiv.org/abs/1810.04805">The paper</a>.</figcaption></figure><p>As you can see, we first train the model on the pre-training tasks simultaneously. Once the pre-training is complete, the same model can be fine-tuned for a variety of downstream tasks. Note that a separate model is fine-tuned for a specific downstream task. So single pre-trained models can generate multiple downstream task specific models post fine tuning.</p><h3>BERT Architecture</h3><p>Simply put, it is <strong><em>a stack of Transformer’s Encoder</em></strong>. You can read about Transformers in details in <a href="https://towardsdatascience.com/transformers-89034557de14">my previous article</a>. Or if you have some faint idea about it already, check out <a href="https://peltarion.com/knowledge-center/documentation/modeling-view/build-an-ai-model/blocks/bert-encoder">this</a> absolutely bomb 3D diagram of the Encoder block used in BERT. <strong>Seriously you can’t miss this!</strong></p><p><a href="https://towardsdatascience.com/transformers-89034557de14">Transformers</a></p><p>Now let’s look at some numbers that none of us will ever remember, but our understanding will feel incomplete without them, so here goes nothing:</p><p><strong>L </strong>= Number of layers (i.e., #Transformer encoder blocks in the stack).<br><strong>H</strong> = Hidden size (i.e. the size of <em>q, k </em>and<em> v </em>vectors).<br><strong>A </strong>= Number of attention heads.</p><ul><li><strong><em>BERT Base</em></strong>: L=12, H=768, A=12.<br>Total Parameters=110M!</li><li><strong><em>BERT Large</em></strong>: L=24, H=1024, A=16.<br>Total Parameters=340M!!</li></ul><h4>What makes it Bidirectional?</h4><p>We usually create a language model by training it on some unrelated task but tasks that help develop a contextual understanding of words in a model. More often than not such tasks involve predicting the next word or words in close vicinity of each other. Such training methods can’t be extended and used for bidirectional models because it would allow each word to indirectly “see itself” — when you would approach the same sentence again but from opposite direction, you kind of already know what to expect. A case of data leakage.</p><p>In such a situation, model could trivially predict the target word. Additionally, we can’t guarantee that the model, if completely trained, has learnt the contextual meaning of the words to some extent and not just focused on optimizing the trivial predictions.</p><p>So how does BERT manage to pre-train bidirectionally? It does so by using a procedure called Masked LM. More details on it later, so read on, my friend.</p><h3>Pre-training BERT</h3><p>The BERT model is trained on the following two unsupervised tasks.</p><h4>1. Masked Language Model (MLM)</h4><p>This task enables the deep bidirectional learning aspect of the model. In this task, some percentage of the input tokens are masked (Replaced with [<em>MASK</em>] token) at random and the model tries to predict these masked tokens — not the entire input sequence. The predicted tokens from the model are then fed into an output softmax over the vocabulary to get the final output words.</p><p>This, however creates a mismatch between the pre-training and fine-tuning tasks because the latter does not involve predicting masked words in most of the downstream tasks. This is mitigated by a subtle twist in how we mask the input tokens.</p><p>Approximately 15% of the words are masked while training, but all of the masked words are not replaced by the [<em>MASK</em>] token.</p><ul><li>80% of the time with [<em>MASK</em>] tokens.</li><li>10% of the time with a random tokens.</li><li>10% of the time with the unchanged input tokens that were being masked.</li></ul><h4>2. Next Sentence Prediction (NSP)</h4><p>The LM doesn’t directly capture the relationship between two sentences which is relevant in many downstream tasks such as <a href="https://towardsdatascience.com/evaluation-of-an-nlp-model-latest-benchmarks-90fd8ce6fae5">Question Answering (QA) and Natural Language Inference (NLI)</a>. The model is taught sentence relationships by training on binarized NSP task.</p><p>In this task, two sentences — A and B — are chosen for pre-training.</p><ul><li>50% of the time B is the actual next sentence that follows A.</li><li>50% of the time B is a random sentence from the corpus.</li></ul><h4>Training — Inputs and Outputs.</h4><p>The model is trained on both above mentioned tasks simultaneously. This is made possible by clever usage of inputs and outputs.</p><h4>Inputs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_d5e72O312RkQkasUJ3EnQ.png" /><figcaption>The input representation for BERT. Source: <a href="https://arxiv.org/abs/1810.04805">The paper</a>.</figcaption></figure><p>The model needs to take input for both a single sentence or two sentences packed together unambiguously in one token sequence. Authors note that a “sentence” can be an arbitrary span of contiguous text, rather than an actual linguistic sentence. A [SEP] token is used to separate two sentences as well as a using a learnt segment embedding indicating a token as a part of segment A or B.</p><p><em>Problem #1:</em> All the inputs are fed in one step — as opposed to RNNs in which inputs are fed sequentially, the model is <strong><em>not able to preserve the ordering</em></strong> of the input tokens. The order of words in every language is significant, both semantically and syntactically.</p><p><em>Problem #2:</em> In order to perform Next Sentence Prediction task properly we need to be able to <strong><em>distinguish between sentences A and B</em></strong>. Fixing the lengths of sentences can be too restrictive and a potential bottleneck for various downstream tasks.</p><p>Both of these problems are solved by adding embeddings containing the required information to our original tokens and using the result as the input to our BERT model. The following embeddings are added to token embeddings:</p><ul><li><strong><em>Segment Embedding</em></strong>: They provide information about the sentence a particular token is a part of.</li><li><strong><em>Position Embedding</em></strong>: They provide information about the order of words in the input.</li></ul><h4>Outputs</h4><p>How does one predict output for two different tasks simultaneously? The answer is by using different FFNN + Softmax layer built on top of output(s) from the last encoder, corresponding to desired input tokens. We will refer to the outputs from last encoder as final states.</p><p>The first input token is always a special classification <em>[CLS] </em>token. The final state corresponding to this token is used as the aggregate sequence representation for classification tasks and used for the Next Sentence Prediction where it is fed into a FFNN + Softmax layer that predicts probabilities for the labels “<em>IsNext</em>” or “<em>NotNext</em>”.</p><p>The final states corresponding to [<em>MASK</em>] tokens is fed into FFNN+Softmax to predict the next word from our vocabulary.</p><h3>Fine-tuning BERT</h3><p>Fine-tuning on various downstream tasks is done by swapping out the appropriate inputs or outputs. In the general run of things, to train task-specific models, we add an extra output layer to existing BERT and fine-tune the resultant model — all parameters, end to end. A positive consequence of adding layers — input/output and not changing the BERT model is that only a minimal number of parameters need to be learned from scratch making the procedure fast, cost and resource efficient.</p><p>Just to give you an idea of how fast and efficient it is, the authors claim that all the results in the paper can be replicated in <em>at most 1 hour</em> on a <em>single Cloud TPU</em>, or <em>a few hours on a GPU</em>, starting from the exact same pre-trained model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKcrS0VO_ZBEysVh-AvL7w.png" /><figcaption>Fine-tuning BERT on various downstream tasks. Source:<a href="https://arxiv.org/abs/1810.04805"> The paper</a>.</figcaption></figure><p>In Sentence Pair Classification and Single Sentence Classification, the final state corresponding to [<em>CLS</em>] token is used as input for the additional layers that makes the prediction.</p><p>In QA tasks, a start (S) and an end (E) vector are introduced during fine tuning. The question is fed as sentence A and the answer as sentence B. The probability of word <em>i</em> being the start of the answer span is computed as a dot product between T<em>i</em> (final state corresponding to <em>i</em>th input token) and S (start vector) followed by a softmax over all of the words in the paragraph. A similar method is used for end span. <br>The score of a candidate span from position <em>i</em> to position <em>j</em> is defined as S·T<em>i</em> + E·T<em>j</em>, and the maximum scoring span where<em> j </em>≥ <em>i</em> is used as a prediction</p><h3>GPT — The distant cousin</h3><p>Is BERT the only model that is producing these ground breaking results? No. Another model by OpenAI, called GPT has been making quite the buzz on internet.</p><p>But what many people don’t realize that these two models have something in common, that is both these model reuse a Transformer component. As stated earlier <strong>BERT stacks the encoder part</strong> of the Transformer as its building block. Meanwhile, <strong>GPT uses the decoder part</strong> of the Transformer as its building block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*dAjV_FHxqONhyFvxO_sBxA.png" /><figcaption>Source: <a href="https://arxiv.org/abs/1810.04805">The paper.</a></figcaption></figure><p>Note that the bidirectional connections in BERT due to encoder’s bidirectional self-attention. Meanwhile, the connections in GPT are only in a single direction, from left-to-right, due to decoder design to prevent looking at future predictions — refer <a href="https://towardsdatascience.com/transformers-89034557de14">Transformers</a> for more info.</p><h3>The BERT Family</h3><p>It wouldn’t be 21st century if we didn’t take something that works well and try to recreate or modify it. BERT architecture is no different. These are some of the most popular variants of it:</p><ul><li><a href="https://arxiv.org/abs/1909.11942"><strong>ALBERT</strong></a> by Google and more — This paper describes parameter reduction techniques to lower memory reduction and increase the training speed of BERT models.</li><li><a href="https://arxiv.org/abs/1907.11692"><strong>RoBERTa</strong></a> by Facebook — This paper for FAIR believes the original BERT models were under-trained and shows with more training/tuning it can outperform the initial results.</li><li><a href="https://arxiv.org/abs/1904.09223"><strong>ERNIE</strong></a>: Enhanced Representation through Knowledge Integration by Baidu — It is inspired by the masking strategy of BERT and learns language representation enhanced by knowledge masking strategies, which includes entity-level masking and phrase-level masking.</li><li><a href="https://arxiv.org/abs/1910.01108"><strong>DistilBERT</strong></a> — Smaller BERT using model distillation from Huggingface.</li></ul><p>You can check out more BERT inspired models at <a href="https://gluebenchmark.com/leaderboard">the GLUE Leaderboard</a>.</p><h3>Conclusion</h3><ol><li>BERT is a stacked Transformer’s Encoder model.</li><li>It has two phases — pre-training and fine-tuning.</li><li>Pre-training is computationally and time intensive.</li><li>It is, however, independent of the task it finally does, so same pre-trained model can be used for a lot of tasks.</li><li>GPT is not that different from BERT and is a stacked Transformer’s decoder model.</li><li>There are many variants of BERT out there.</li></ol><h3>References + Recommended Reads</h3><ul><li><a href="https://towardsdatascience.com/transformers-89034557de14">Transformers</a> — if you want more in-depth knowledge on aforementioned encoder/decoder architecture.</li><li><a href="https://arxiv.org/abs/1810.04805">The paper</a> — it is easy to read, and they also elaborate on the practical details a bit. Worth a read.</li><li><a href="http://jalammar.github.io/illustrated-bert/">Jay Alammar’s Blog</a>.</li><li><a href="https://github.com/google-research/bert">Official GitHub repo.</a></li><li><a href="https://towardsdatascience.com/2019-year-of-bert-and-transformer-f200b53d05b9">More BERT Models</a>.</li></ul><blockquote><em>I’m glad you made it till the end of this article. 🎉<br>I hope your reading experience was as enriching as the one I had writing this. 💖</em></blockquote><blockquote><em>Do check out my other articles </em><a href="https://medium.com/@ria.kulshrestha16"><em>here</em></a><em>.</em></blockquote><blockquote><em>If you want to reach out to me, my medium of choice would be </em><a href="https://twitter.com/ree_____ree"><em>Twitter</em></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b7beb92766" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/keeping-up-with-the-berts-5b7beb92766">Keeping up with the BERTs</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Books You Can’t Forget]]></title>
            <link>https://ria-kulshrestha.medium.com/books-you-cant-forget-194c26ca5997?source=rss-406aa3cbd38e------2</link>
            <guid isPermaLink="false">https://medium.com/p/194c26ca5997</guid>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[book-recommendations]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[reading]]></category>
            <dc:creator><![CDATA[Ria Kulshrestha]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 10:25:00 GMT</pubDate>
            <atom:updated>2023-03-11T03:37:34.586Z</atom:updated>
            <content:encoded><![CDATA[<h4>According to my friends from Instagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zeqzThX6qXB8abZt" /><figcaption>Photo by <a href="https://unsplash.com/@haticehuma?utm_source=medium&amp;utm_medium=referral">Hatice Yardım</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In times dim and distant, I asked followers on my <a href="https://www.instagram.com/__ree.ree_/?hl=en">Instagram</a> account to share “<strong><em>Books that they couldn’t forget!</em></strong>”, and they didn’t disappoint. The past me was lazy and compiled them in a Google Doc, but here goes nothing!</p><h4><strong><em>Disclaimers:</em></strong></h4><ol><li>I haven’t read most of these books.</li><li>I also haven’t dared to sort them into genres owing to my unawareness of their content.</li><li>It is an eternal WIP and I would be more than happy to add your unforgettable books to this list. I would also like to mention your name along with the recommendation for tracking purposes — only if you are ok with that.</li><li>The post is hastily put together and would improve considerably — both in terms of visuals and formatting — in future.</li></ol><h3>The Book Recommendations — in no particular order:</h3><ul><li><a href="https://www.goodreads.com/book/show/27220736-shoe-dog"><strong>Shoe Dog</strong></a> by Phil Knight &lt;- read it and it is good and kinda motivates you, if you are struggling to “<em>Just Do It</em>” this might be the push you need.</li><li><a href="https://www.goodreads.com/book/show/34890015-factfulness?ref=nav_sb_ss_1_7"><strong>Factfulness: Ten Reasons We’re Wrong About the World — and Why Things Are Better Than You Think</strong></a> by Hans Rosling, Ola Rosling, Anna Rosling Rönnlund &lt;- could have used a shorter title, haven’t read it to have an opinion beyond this.</li><li><strong>21 Lessons for the 21st Century</strong> by Yuval Noah Harari</li><li><strong>Sapiens: A Brief History of Humankind</strong> by Yuval Noah Harari</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uwMr98tq1CkLx-0E" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li><strong>1984 </strong>by George Orwell &lt;- Makes you think a lot and is not just about totalitarian governments. I rather thought that was just a small bit of it.</li><li><strong>The Subtle Art of Not Giving a F*#K</strong> by Mark Manson</li><li><strong>A Thousand Splendid Suns</strong> by Khaled Hosseini &lt;- Really emotional and moving. It is about a women in Afghanistan and her courage and sacrifice. Don’t want to spoil it much but emotions were felt.</li><li><strong>The Kite Runner</strong> by Khaled Hosseni &lt;- Similar scene (Afghanistan under Taliban) as the above but a very different story. Reading both makes you realise how a situation impacts everyone differently.</li><li><strong>Into Thin Air</strong> by Jon Krakauer</li><li><strong>“Surely You’re Joking, Mr. Feynman!”</strong> by Richard P. Feynman</li><li><strong>How to Get Rich and Retire Earl</strong>y by Raja Sekharan</li><li>Nudge (couldn’t resolve the exact book)</li><li><strong>The Leader Who Had No Title</strong> by Robin S. Sharma</li><li><strong>The Checklist Manifesto </strong>by Atul Gawande</li><li><strong>A Stranger in the Mirror</strong> by Sidney Sheldon</li><li><strong>Flowers for Algernon</strong> by Daniel Keyes</li><li><strong>Deep Work</strong> by Cal Newport &lt;- Started it and I think it is crucial in the current times, but due to some other priorities couldn’t finish and had to return my copy to the library. But it is quite high in my non fiction TBR list.</li><li><strong>If Tomorrow Comes</strong> by Sidney Sheldon</li><li><strong>The Book Thief</strong> by Markus Zusak</li><li><strong>Kafka on the Shore</strong> by Haruki Murakami</li><li><strong>To Kill A Mockingbird </strong>by Harper Lee &lt;- An American classic, views racism from a white kids POV. Though you can find much better reviews online.</li><li><a href="https://www.goodreads.com/book/show/38746485-becoming?ref=nav_sb_ss_1_5"><strong>Becoming</strong></a> by Michelle Obama &lt;- Loved it. A strong, ambitious and smart women. Really enjoyed reading it and how she navigates life. Honestly could re-read it!</li><li><strong>When Breath Becomes</strong> Air by Paul Kalanithi</li><li><strong>Tuesdays with Morrie</strong> by Mitch Albom</li><li><a href="https://www.goodreads.com/book/show/18405.Gone_with_the_Wind"><strong>Gone With The Wind</strong></a> by Margaret Mitchell</li><li><a href="https://www.goodreads.com/book/show/5345.The_Innocent_Man?ref=nav_sb_ss_1_16"><strong>The Innocent Man: Murder and Injustice in a Small Town</strong></a> by John Grisham</li><li><a href="https://www.goodreads.com/book/show/3228917-outliers?ref=nav_sb_ss_1_7"><strong>Outliers</strong></a> by Adam Grant</li><li><a href="https://www.goodreads.com/book/show/22628.The_Perks_of_Being_a_Wallflower?ref=nav_sb_ss_1_10"><strong>The Perks of Being a Wallflower</strong></a> by Stephen Chbosky</li><li><a href="https://www.goodreads.com/book/show/7302394-blonde-bombshell?ac=1&amp;from_search=true&amp;qid=7OTtrcai1A&amp;rank=2"><strong>Blonde Bombshell</strong></a> by Tom Holt</li></ul><h3>Series</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q9vCFh_B3OnbRV85" /><figcaption>Photo by <a href="https://unsplash.com/@itsmaemedia?utm_source=medium&amp;utm_medium=referral">Shayna Douglas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li><a href="https://www.goodreads.com/series/45175-harry-potter"><strong>Harry Potter</strong></a> by JK Rowling &lt;- It is a childhood crush that I read at the cusp of adulthood. It might not be the best/most immersive fantasy but it made me love reading and you can’t deny it feels nice to be a part of the Potter-verse, with the memes and references.</li><li><a href="https://www.goodreads.com/series/108715-warbreaker"><strong>Warbreaker</strong></a> by Brandon Sanderson &lt;- I have read Mistborn trilogy and really enjoyed it, from the reviews I have found it is supposedly even better.</li><li><a href="https://www.goodreads.com/series/40739-the-belgariad"><strong>The Belgariad</strong></a><strong> </strong>series by David Eddings</li><li><a href="https://www.goodreads.com/series/66428-the-clifton-chronicles"><strong>The Clifton Chronicles</strong></a> by Jeffrey Archer &lt;- I have read a few of his books and they are good and but there are usually too many in a series for me to commit to.</li><li><a href="https://www.goodreads.com/series/44598-millennium"><strong>Millennium</strong></a> by Steig larsson &lt;- You might know its first book, the girl with the dragon tattoo.</li></ul><p><strong><em>Thank you everyone!</em></strong></p><p>Some bonus recommendations from my side — because ain’t no thing as too many recommendations:</p><blockquote>“Becoming is better than being”</blockquote><ul><li><a href="https://www.goodreads.com/book/show/40745.Mindset">Mindset: The New Psychology of Success</a> by Carol C. Dweck<br>The idea might get a little repetitive for people by the end but basic premise is sound.</li></ul><blockquote>“It was when he tried to talk about ‘the boat’ that his words began to falter and tears welled up in his eyes…Finally, watching Joe struggle for composure over and over, I realised that ‘the boat’ was something more than just the shell or its crew. To Joe, it encompassed but transcended both — it was something mysterious and almost beyond definition. It was a shared experience — a singular thing that had unfolded in a golden sliver of time long gone, when nine good-hearted young men strove together, pulled together as one, gave everything they had for one another, bound together forever by pride and respect and love. Joe was crying, at least in part, for the loss of that vanished moment but much more, I think, for the sheer beauty of it.”</blockquote><ul><li>The Boys in the Boat by Daniel James Brown &lt;- never thought I would care much about rowing but here we are, that’s the power of good story telling.</li></ul><blockquote>“Happiness comes from moving toward something. When you run away, ofttimes you bring your misery with you.”</blockquote><ul><li>The Riyria Revelations by Michael J. Sullivan &lt;- the richer fantasy I was talking about earlier. This is a good example.</li></ul><h3>Want to add your books to this list?</h3><p>Just reach out to me anywhere or leave a note on this post, and I will add your book recommendations to this list. :)</p><p><em>I‘m glad you made it till the end of this article. </em>🎉 <br><em>If you liked this article, do share it with your friends/family or leave a few claps. </em>💖</p><p><em>Do check out my other articles </em><a href="https://medium.com/@ria.kulshrestha16"><em>here</em></a><em>.</em></p><p><em>If you want to reach out to me, my medium of choice would be </em><a href="https://twitter.com/ree_____ree"><em>Twitter</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=194c26ca5997" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers]]></title>
            <link>https://medium.com/data-science/transformers-89034557de14?source=rss-406aa3cbd38e------2</link>
            <guid isPermaLink="false">https://medium.com/p/89034557de14</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Ria Kulshrestha]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 08:44:31 GMT</pubDate>
            <atom:updated>2020-11-22T11:01:46.716Z</atom:updated>
            <content:encoded><![CDATA[<h4>Or as I like to call it Attention on Steroids. 💉💊</h4><figure><img alt="A picture of Transformer from the movie franchise." src="https://cdn-images-1.medium.com/max/1024/0*2YfRrpQtt8TG2iuz" /><figcaption>Photo by <a href="https://unsplash.com/@tetrakiss?utm_source=medium&amp;utm_medium=referral">Arseny Togulev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>No, this article is not about the American sci-fi action movie series — no Optimus Prime here. It is also not about the electrical device that is used to transfer energy from one electrical circuit to another. What is this about then, you ask?</p><p>It is about the one in the most sci-fi fields of all time, Artificial Intelligence — Natural Language Processing in particular and it is pretty optimal at transferring information and primely used. (See what I did there. :P)</p><p>This post is based on the paper: <a href="https://arxiv.org/abs/1706.03762">Attention is All You Need</a>. P.S. the authors were not kidding when they chose that title because you will need all the attention at your disposal for this one. But don’t let that scare you, it is SO SO worth it!!</p><h3>What is a Transformer?</h3><p>The Transformer in NLP is a <strong>novel architecture</strong> that aims to solve sequence-to-sequence tasks while handling long-range dependencies with ease. It relies entirely on self-attention to compute representations of its input and output <strong>WITHOUT</strong> using sequence-aligned RNNs or convolution. 🤯</p><p>If you recall my previous post, <a href="https://towardsdatascience.com/attaining-attention-in-deep-learning-a712f93bdb1e">Understanding Attention In Deep Learning</a>, we discussed how and why many models fell short when it came to handling long-range dependencies. The concept of attention somewhat allowed us to overcome that problem and now in Transformers we will build on top of attention and unleash its full potential.</p><p><a href="https://towardsdatascience.com/attaining-attention-in-deep-learning-a712f93bdb1e">Understanding Attention In Deep Learning</a></p><h3>Few things to know before diving into Transformers</h3><h4>Self-Attention</h4><p>Let us start with revisiting what attention is in the NLP universe? <a href="https://towardsdatascience.com/attaining-attention-in-deep-learning-a712f93bdb1e">Understanding Attention In Deep Learning</a>. (<em>I apologize for these blatant self-advertisements, but seriously give it a read. It will help you under Transformers much better. I promise.</em>)</p><p><strong><em>Attention allowed us to focus on parts of our input sequence while we predicted our output sequence</em></strong>. If our model predicted the word “<em>rouge</em>” [French translation for the color red], we are very likely to find a high weight-age for the word “<em>red</em>” in our input sequence. So attention, in a way, allowed us to map some connection/correlation between the input word “<em>rouge</em>” and the output word “<em>red</em>”.</p><blockquote><strong>Self attention</strong>, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence.</blockquote><p>In simpler terms, <strong><em>self attention helps us create similar connections but within the same sentence.</em></strong> Look at the following example:</p><pre>“I poured water from the <em>bottle</em> into the <strong><em>cup</em></strong> until <strong>it</strong> was <strong><em>full</em></strong>.”<br>it =&gt; cup</pre><pre>“I poured water from the <strong>bottle</strong> into the cup until <strong>it</strong> was <strong><em>empty</em></strong>.”<br>it=&gt; bottle</pre><p>By changing one word “<em>full</em>” — &gt; “<em>empty</em>” the reference object for “<em>it</em>” changed. If we are translating such a sentence, we will want to know the word “<em>it</em>” refers to.</p><h4>The three kinds of Attention possible in a model:</h4><ol><li><strong><em>Encoder-Decoder Attention</em>: </strong>Attention between the input sequence and the output sequence.</li><li><strong><em>Self attention in the input sequence</em>:</strong> Attends to all the words in the input sequence.</li><li><strong><em>Self attention in the output sequence:</em></strong> One thing we should be wary of here is that the scope of self attention is limited to the words that occur before a given word. This prevents any information leaks during the training of the model. This is done by masking the words that occur after it for each step. So for step 1, only the first word of the output sequence is NOT masked, for step 2, the first two words are NOT masked and so on.</li></ol><h4>Keys, Values, and Queries:</h4><p>The three random words I just threw at you in this heading are vectors created as abstractions are useful for calculating self attention, more details on each below. These are calculated by multiplying your input vector(<em>X</em>) with weight matrices that are learnt while training.</p><ul><li><strong><em>Query Vector</em></strong>: <em>q</em>= <em>X * Wq. </em>Think of this as the current word.</li><li><strong><em>Key Vector</em></strong><em>:</em> <em>k</em>= <em>X * Wk. </em>Think of this as an indexing mechanism for Value vector. Similar to how we have key-value pairs in hash maps, where keys are used to uniquely index the values.</li><li><strong><em>Value Vector:</em></strong> <em>v</em>= <em>X * Wv. </em>Think of this as the information in the input word.</li></ul><p>What we want to do is take query <em>q </em>and find the most similar key <em>k</em>, by doing a dot product for <em>q </em>and <em>k</em>. The closest query-key product will have the highest value, followed by a softmax that will drive the <em>q.k </em>with smaller values close to 0 and <em>q.k </em>with larger values towards 1. This softmax distribution is multiplied with <em>v. </em>The value vectors multiplied with ~1 will get more attention while the ones ~0 will get less. The sizes of these <em>q, k </em>and<em> v </em>vectors are referred to as “<strong><em>hidden size</em></strong>” by various implementations.</p><figure><img alt="Showed how q and k are softmax-ed and then a dot product with gives us the final output." src="https://cdn-images-1.medium.com/max/1024/1*rq5m4VKziz2CvblZ70sKjA.png" /><figcaption>The values represent the index for q, k and i.</figcaption></figure><p>All these matrices <em>Wq, Wk</em> and <em>Wv</em> are learnt while being jointly trained during the model training.</p><h4>Calculating Self attention from q, k and v:</h4><figure><img alt="Formula for attention. Do Q dot K, divide by square root of dim of K. Take softmax and lastly multiply with V." src="https://cdn-images-1.medium.com/max/637/1*-B9pI_0xI9M4air8x_ggYA.png" /><figcaption>Formula for self-attention. Source: paper.</figcaption></figure><p>If we are calculating self attention for <em>#i</em> input word,</p><ul><li><strong><em>Step 1:</em></strong> Multiply qᵢ by the kⱼ key vector of word.</li><li><strong><em>Step 2:</em></strong> Then divide this product by the square root of the dimension of key vector. <br>This step is done<strong> for better gradient flow </strong>which is specially important in cases when the value of the dot product in previous step is too big. As using them directly might push the softmax into regions with very little gradient flow.</li><li><strong><em>Step 3:</em></strong> Once we have scores for all <em>j</em>s, we pass these through a softmax. We get normalized value for each <em>j</em>.</li><li><strong><em>Step 4:</em></strong> Multiply softmax scores for each <em>j</em> with <em>v</em>ᵢ<em> </em>vector. <br>The idea/purpose here is, very similar attention, to keep preserve only the values <em>v </em>of the input word(s) we want to focus on by multiplying them with high probability scores from softmax ~1, and remove the rest by driving them towards 0, i.e. making them very small by multiplying them with the low probability scores ~0 from softmax.</li></ul><figure><img alt="The calculation at each step shown mathematically." src="https://cdn-images-1.medium.com/max/743/1*jbqL3JWQyLFVgNgYyOGKhg.png" /><figcaption>Calculating output of self attention for the ith input word. If you are looking for an analogy between self attention and attention, think of z serving the purpose of context vectors and not global alignment weights.</figcaption></figure><h3>The Transformer</h3><p>⚠️ <strong><em>A word of caution</em></strong>: the contents of this image may appear exponentially more complicated than they are. We will break this scary beast down into small baby beasts and it will all make sense. (I promise #2)</p><figure><img alt="The architecture of Transformer from the paper with encoder, decoder and pre-processing parts labelled." src="https://cdn-images-1.medium.com/max/1024/1*iy12bH-FiUNOy9-0bULgSg.png" /><figcaption>(left) The Transformer architecture. Source: paper. (right) An abstracted version of the same for better understanding.</figcaption></figure><h4>Beast #1: Encoder-Decoder stacks</h4><p><strong><em>Encoder</em></strong>: The encoder maps an input sequence of symbol representations <em>(x</em>₁<em>, …, x</em>ₙ<em>)</em> to a sequence of representations <em>z = (z</em>₁<em>, …, z</em>ₙ<em>)</em>. Think of them as the outputs from self attention with some post-processing.</p><p>Each encoder has two sub-layers.</p><ol><li>A <strong>multi-head self attention mechanism</strong> on the input vectors (Think parallelized and efficient sibling of self attention).</li><li>A simple, position-wise <strong>fully connected feed-forward network</strong> (Think post-processing).</li></ol><p>Check out <a href="https://peltarion.com/knowledge-center/documentation/modeling-view/build-an-ai-model/blocks/bert-encoder">this</a> absolute bomb 3D diagram of the Encoder block used in <a href="https://medium.com/@ria.kulshrestha16/keeping-up-with-the-berts-5b7beb92766">BERT</a>. <strong>Seriously you can’t miss this!!! </strong>It is like a whole new level of understanding.</p><p><strong><em>Decoder</em></strong>: Given <em>z</em>, the decoder then generates an output sequence <em>(y</em>₁<em>, …, y</em>ₘ<em>)</em> of symbols one element at a time.</p><p>Each decoder has three sub-layers.</p><ol><li>A <strong><em>masked</em></strong> <strong>multi-head self attention mechanism </strong>on the output vectors of the previous iteration.</li><li>A <strong>multi-head attention mechanism </strong>on the output from encoder and masked multi-headed attention in decoder.</li><li>A simple, position-wise <strong>fully connected feed-forward network</strong> (think post-processing).</li></ol><p>A few additional points:</p><ul><li>In the original paper, 6 layers were present in the encoder stack (2 sub-layer version) and 6 in the decoder stack (3 sub-layer version).</li><li>All sub-layers in the model, as well as the embedding layers, produce outputs of the same dimension. This is done to facilitate the residual connections.</li></ul><h4>Beast #2 Inside Encoder-Decoder stacks — Multi-Head Attention:</h4><figure><img alt="Diagram showing where each kind of attention is calculated in the architecture." src="https://cdn-images-1.medium.com/max/1024/1*9UJYSFUpPlx1cLMPCm7ACw.png" /><figcaption>The three kinds of attention in encoder and decoder stacks along with feed forward neural networks.</figcaption></figure><p>We just noted that the output of each sub-layer needs to be of the same dimension which is 512 in our paper.<br>=&gt; zᵢ needs to be of 512 dimensions. <br>=&gt; vᵢ needs to be of 512 dimensions as zᵢ are just sort of weighted sums of vᵢs.</p><p>Additionally, we want to allow the model to focus on different positions is by <strong>calculating self attention multiple times with different sets</strong> of <em>q, k </em>and <em>v</em> vectors, then take an average of all those outputs to get our final <em>z</em>.</p><p>So instead of dealing with these humongous vectors and averaging multiple outputs, we reduce the size of our <em>k,q</em> and <em>v</em> vectors to some smaller dimension — reduces size of <em>Wq, Wk</em>, and <em>Wv</em> matrices as well. We keep the multiple sets (<em>h</em>) of <em>k,q</em> and <em>v and </em>refer to each set as an “<em>attention head”,</em> hence the name <em>multi-headed</em> attention. And lastly, instead of averaging to get final <em>z</em>, we concatenate them.</p><p>The size of the concatenated vector will be too large to be fed to the next sub-layer, so we scale it down by multiplying it with another learnt matrix <em>Wo</em>.</p><figure><img alt="Steps to calculate dot product attention and multi headed attention, taken from the paper." src="https://cdn-images-1.medium.com/max/1024/1*NMTM422Crac6Joostx0rOw.png" /><figcaption>(left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel. Source: paper.</figcaption></figure><p>Multiple attention heads allowed the model to jointly attend to information from different representation sub-spaces at different positions which was inhibited by averaging in a single attention head.</p><h4>Beast #3— Input and Output Pre-processing:</h4><p>The input words are represented using some form of embedding. This is done for both encoder and decoder.</p><p>Word embedding on their own lack any positional information which is achieved in RNNs by virtue of their sequential nature. Meanwhile in self-attention, due to softmax, any such positional information is lost.</p><p>To preserve the positional information, the transformer injects a vector to individual input embeddings (could be using word embeddings for corresponding to the input words). These vectors follow a specific periodic function (Example: combination of various sines/cosines having different frequency, in short not in sync with each other) that the model learns and is able to <strong>determine the position of individual word wrt each other </strong>based on the values <strong>.</strong></p><p>This injected vector is called “<em>positional encoding</em>” and are added to the input embeddings at the bottoms of both encoder and decoder stacks.</p><h4>Beast #4 — Decoder stack: Revisited</h4><p>The output of the decoder stack at each step is fed back to the decoder in the next time step — pretty similar to how outputs from previous steps in RNNs were used as next hidden states. And just as we did with the encoder inputs, we embed and add positional encoding to those decoder inputs to preserve the position of each word. This positional encoding + word embedding combo is then fed into a masked multi-headed self attention.</p><p>This self-attention sub-layer in the decoder stack is modified to prevent positions from attending to subsequent positions — you can’t look at future words. This masking ensures that the predictions for position <em>i</em> can depend only on the known outputs at positions less than <em>i</em>.</p><p>The outputs from the encoder stack are then used as multiple sets of key vectors <strong><em>k </em></strong>and value vectors <strong><em>v</em></strong>, for the “encoder decoder attention” — shown in green in the diagram — layer. It helps the decoder focus on the contextually relevant parts in the input sequence for that step. (The part similar to global attention vectors.) The <strong><em>q</em></strong><em> </em>vector comes from the “output self attention” layer.</p><p>Once we get the output from the decoder, we do a softmax again to select the final probabilities of words.</p><h3>Conclusion</h3><p>Let’s finish with a quick wrap-up revision.</p><ul><li>We started with understanding what self attention is and how to calculate self-attention from these <em>v, k ,q </em>vectors.</li><li>Multi-headed attention is an efficient modification of self attention that uses multiple smaller sets of <em>v, k ,q </em>and concatenates the outputs from each set to get the final <em>z.</em></li><li>Then we saw how and where the three kinds of self attention are used in the model.</li><li>Followed by the pre-processing done on the inputs for the encoder and decoder stacks.</li></ul><h3>References + Recommended Reads</h3><ul><li><a href="https://towardsdatascience.com/attaining-attention-in-deep-learning-a712f93bdb1e">Understanding Deep Attention in Deep Learning</a> if you faced issues around attention.</li><li><a href="http://jalammar.github.io/illustrated-transformer/">The Illustrated Transformer</a> — Has great visualizations along with the explanations.</li><li><a href="https://www.analyticsvidhya.com/blog/2019/06/understanding-transformers-nlp-state-of-the-art-models/">https://www.analyticsvidhya.com/blog/2019/06/understanding-transformers-nlp-state-of-the-art-models/</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiDulhoQ2pro%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiDulhoQ2pro&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiDulhoQ2pro%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8219452f400a63ace3780aae70b1bbc0/href">https://medium.com/media/8219452f400a63ace3780aae70b1bbc0/href</a></iframe><ul><li>YouTube video #1: A great resource to get the model intuition. Specially if you want to <strong>learn more about positional encoding.</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrBCqOTEfxvg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrBCqOTEfxvg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrBCqOTEfxvg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a51379ef1805b85aa6460bbf57d77d71/href">https://medium.com/media/a51379ef1805b85aa6460bbf57d77d71/href</a></iframe><ul><li>YouTube video#2: Talk by Lukasz Kaiser on this <strong>paper explaining self attention</strong> — . P.S. He is one of the authors for this paper.</li></ul><blockquote>I’m glad you made it till the end of this article. <em>🎉</em><br>I hope your reading experience was as enriching as the one I had writing this. <em>💖</em></blockquote><blockquote>If you liked this article, do check out my other ones <a href="https://medium.com/@ria.kulshrestha16">here</a>.</blockquote><blockquote>If you want to reach out to me, my medium of choice would be <a href="https://twitter.com/ree_____ree">Twitter</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89034557de14" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/transformers-89034557de14">Transformers</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Attention In Deep Learning]]></title>
            <link>https://medium.com/data-science/attaining-attention-in-deep-learning-a712f93bdb1e?source=rss-406aa3cbd38e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a712f93bdb1e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[attention]]></category>
            <dc:creator><![CDATA[Ria Kulshrestha]]></dc:creator>
            <pubDate>Fri, 08 May 2020 19:13:08 GMT</pubDate>
            <atom:updated>2020-10-28T22:19:49.151Z</atom:updated>
            <content:encoded><![CDATA[<h4>How a little attention changed the AI game!</h4><figure><img alt="A girl looking into a lens. Just a pretty cover picture, nothing much to do with the article." src="https://cdn-images-1.medium.com/max/1024/0*3WEpWAkyXjUHbNbG" /><figcaption>Photo by <a href="https://unsplash.com/@haneenkrimly?utm_source=medium&amp;utm_medium=referral">Haneen Krimly</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In one of my <a href="https://medium.com/analytics-vidhya/the-price-of-free-d662016a5229?source=friends_link&amp;sk=924bc170af02df5b9c38b6e99965a136">previous articles</a>, I talk about how attention is one of the most important assets — we as humans — have. How we choose to spend our time and on what we choose to focus on during that time determines the outcome for almost all our endeavors.</p><p>In this article, we will discuss how we gave an ML model the ability to focus and the impact it had on its performance.</p><h3>Why models need to have attention</h3><p>Let’s go over a task — popularly solved in many NLP models — translation. A word to word translation doesn’t work in most cases as most languages don’t share a common sentence structure. A simple example:</p><pre>English =&gt; French<br>red =&gt; rouge<br>dress =&gt; robe<br>“<em>red dress</em>” =&gt; “<em>robe rouge</em>”<br>Notice how red is before dress in English but rouge is after robe.</pre><p>The way NLP models usually go about such tasks is by capturing all the information in the input sentence —the details of objects, how objects are related to each other — in an intermediate state and then using this intermediary information and expressing it in the output language. The size of the vector used for this intermediary state i.e. the state capturing all the information from input sequence — before we start decoding the output sequence— is fixed.</p><figure><img alt="How RNNs based models usually work, by creating intermediate fixed size vectors, in case of language translation" src="https://cdn-images-1.medium.com/max/1024/1*7Lq2Adl1gfRIP5S1D9tYtQ.png" /><figcaption>How NLP models translate from input to output sequence. The input sequence and the encoder model are shown in yellow, while the output sequence and the decoder model are shown in blue. <strong>Note the t in the encoder model has no correlation with the one in the decoder model, and is just used to represent the next time step in each of the models.</strong></figcaption></figure><p>The intermediate state plays a paramount role in this entire process. Its ability to remember all the information passed in the input sentence is critical to the quality of decoded output. Whether it is a translation or a QnA task, in which the input is a question and a paragraph and the model needs to predict the answer to that question based on the paragraph or, any other sequence to sequence modeling operation, the intermediary state continues to be the most crucial piece of the puzzle.</p><blockquote>It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way — in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.</blockquote><blockquote>- A Tale of Two Cities, Charles Dickens.</blockquote><p>Now I ask you to just memorize, not even translate, this sentence after going over it once, from left to right, and I limit the number of words that you can write in your notes. Not so easy, is it?</p><p>How about memorizing this sentence about cars brimming with facts that I totally made up? <em>Disclaimer: The numbers and use cases appearing in the following statement are fictitious, any sense they make is purely coincidental.</em></p><blockquote>This car is 2m in <strong>height</strong> — so lean on my friend, 12m in <strong>width</strong> — not very hug-able unfortunately, with a 8m <strong>wheelbase</strong> — whatever use that information is for, a <strong>turning radius</strong> of just 0.1m — making it easier to turn away from all your problems, a <strong>boot-space</strong> of 200 litres — for all the luggage you’ll carry for a trip and never use, a <strong>ground clearance</strong> of 0.25m — in case you ever seek refuge under the car, a 6 <strong>cylinder engine</strong> with 5 <strong>valves</strong> — a spec you’ll only ever use while showing off and lastly has a <strong>dual overhead camshaft</strong> because big cars comes with big words. <br>-Yours truly :)</blockquote><p>Jokes aside, in this case not only you have to remember all the numbers I randomly threw in there, but also the features —shown in bold — it corresponds to. Mess it up at one place and you have got it all wrong.</p><p>As evident by now, in <strong>cases with very long sentences as input, the intermediate state fails and is not sufficient to capture all the information.</strong> Often it will forget the first part by the time it completes processing the whole input. To improve the model’s performance and relieve the intermediate state from being solely responsible for encoding all the information available to the decoder in a fixed length vector and from being a potential bottleneck, we use the concept of <strong><em>attention</em></strong>. With this new approach, the information can be spread throughout the sequence of annotations — encoder hidden states, which can be selectively retrieved by the decoder accordingly.</p><h3>Attention mechanism in a model</h3><p>Attention mechanism tries to overcome the information bottleneck of the intermediary state by <strong>allowing the decoder model to access all the hidden states</strong>, rather than a single vector — aka intermediary state — build out of the encoder’s last hidden state, while predicting each output.</p><figure><img alt="Current hidden state is a function of 3 things, shown mathematically as a function of them." src="https://cdn-images-1.medium.com/max/385/1*a6Uq7O8_SVarfyzGbNUi0A.png" /><figcaption>Calculating the next hidden state for the decoder model.</figcaption></figure><p>The input to a cell in decoder now gets the following values:</p><ol><li>The previous hidden state of the decoder model Hₖ<em>-</em>₁.</li><li>The previous output of decoder model Yₖ<em>-</em>₁.</li><li>A context vector Cₖ— a weighted sum of <strong>all</strong> encoder hidden states(hⱼ<em>’s</em>) aka annotations. <em>(New addition)</em></li></ol><figure><img alt="How attention fits into current RNNs based models. N (input):1(output) relationship at each output vector." src="https://cdn-images-1.medium.com/max/1001/1*OTQIuyXW6HEOogL0QYxC8A.png" /><figcaption>My take on the image in <a href="https://arxiv.org/pdf/1409.0473.pdf">the original paper</a>. I have not shown the intermediary state in this diagram to keep it simple. h<em>t(the last encoder hidden state) will be the intermediary state and it will be fed, as in input in the first step to the decoder model.</em></figcaption></figure><h4>A few features of Context Vector and Global Alignment Weights</h4><p>The global alignment weights are important because they tell us which annotations(s) to focus on for the next output. The weights will and should vary in each time steps of the decoder model. They are calculated by using a feed forward neural network.</p><figure><img alt="A visual depection of attention from paper shown as a matrix with input on one side and output on the other." src="https://cdn-images-1.medium.com/max/628/1*GW8e-gElo3Cc3afepiFwUA.png" /><figcaption>“The x-axis and y-axis of each plot correspond to the words in the source sentence (English) and the generated translation (French), respectively. Each pixel shows the weight αij of the annotation of the j-th source word for the i-th target word (see Eq. (6)), in grayscale (0: black, 1: white)” — <a href="https://arxiv.org/pdf/1409.0473.pdf">The original paper.</a></figcaption></figure><p>A few observations worth noting:</p><ul><li>While predicting the next step, weights are high — shown in white — only for a few words at a time. No more than 3–4 words have high attention for a given output word.</li><li>The attention doesn’t linger for very long on a particular input word across time steps. That is, just because the weight was high in the previous step, doesn’t imply it would be in the subsequent steps.</li><li>Sometimes attention returns to an input word — look at the word “<em>que</em>” in output and how a part of its attention is on the first word “<em>It</em>”.</li></ul><h4>The flow while predicting — during testing/validation of the model</h4><p>The sequence of steps is as follows:</p><p><strong>ENCODER MODEL:</strong></p><ul><li><strong><em>Step 1</em>:</strong> Run the input sequence to get all the hidden states and calculate the intermediary state.</li></ul><p><strong>DECODER MODEL:</strong></p><ul><li><strong><em>Step 2:</em></strong> Get the global alignment weights ⍺ₖ ⱼ from the attention layer neural network for <em>k</em>ᵗʰ step.</li><li><strong><em>Step 3:</em></strong> Calculate the context vector by multiplying the ⍺ₖ ⱼ<em> </em>with hⱼ<em> </em>for j in range 0 to <em>t, where t=</em>steps in encoder model.</li></ul><figure><img alt="Formula for context vector shown mathematically. C i is summation of all alpha i j dot H j over all Js." src="https://cdn-images-1.medium.com/max/297/1*UzRy-BYgILQj4Hq3dccbqg.png" /><figcaption>The formula for calculating context vector. For our step 3, i = k.</figcaption></figure><ul><li><strong><em>Step 4:</em></strong> Take the previous hidden state of the decoder, Hₖ<em>-</em>₁<em>,</em>the context vector Cₖ<em>, </em>and the previous output Yₖ<em>-</em>₁<em> </em>to get the next hidden state of the decoder Hₖ<em>. </em>Predict Yₖ from Hₖ.</li><li><strong><em>Step 5:</em></strong> Repeat 2, 3 and 4 till model predicts end token.</li></ul><h4>How to get the Global Alignment Weights</h4><p>We know we use a feed forward neural network that outputs these global alignment weights <strong>⍺ₖ ⱼ</strong>. The purpose of these weights is to reflect the importance of each annotation hⱼ w.r.t. the previous hidden state in deciding the next state Hₖ. This, in a way, allows the model to decide which parts of the input to attend to. The bigger the weight, the more attention it gets. So the next question is, what are its inputs, and how do we train it?</p><h4><strong>The Inputs</strong></h4><p>We input both decoder hidden state and the annotations in our neural network to predict a single value — e<strong>ₖ ⱼ</strong> as the authors of the paper liked to call it, the “<strong>associated energy”</strong>— signifying the importance of the annotations in next decoder step Hₖ. We repeat this process for all annotations. Once, we have associated energies corresponding to all annotations, we do a softmax to obtain the <strong>global alignment weights</strong> ⍺ₖ ⱼ.</p><figure><img alt="Associated energy for i j shown mathematically as a function of ith -1 output hidden state and jth input hidden state." src="https://cdn-images-1.medium.com/max/217/1*IehdJ-RKMW6WMRS3NQRgiw.png" /><figcaption>The neural network takes in the ith hidden state of the decoder and the jth hidden state if the encoder to predict each eij, the <strong>associated energy</strong>. For us i=k, as we are doing it for the kth time step in decoder model.</figcaption></figure><figure><img alt="Formula for global alignment weights. exponent of e ij divided by summation of exp e ik where k= 1 to last input hidden state" src="https://cdn-images-1.medium.com/max/288/0*HB5w1t-84ImkX_gB.png" /><figcaption><strong>Global Alignment Weights</strong>: Each weight is a Softmax on outputs(eij) from the neural network.</figcaption></figure><p>Step 2, mentioned before, can now be broken down as follows:</p><ul><li><strong><em>Step 2.a:</em></strong> Calculate eₖ ⱼ where j = 0 to t, t = time steps in encoder model. The decoder hidden state will be the same for all j and will be Hₖ<em>-</em>₁.</li></ul><figure><img alt="energy kj as a function of output hidden state k-1 and input hidden state j." src="https://cdn-images-1.medium.com/max/240/1*ZMHhrdK7sHv0eE6eS92njA.png" /><figcaption>For j = 0 to t, i.e. for all hidden states in encoder.</figcaption></figure><ul><li><strong><em>Step 2.b:</em></strong> Once we have all eₖⱼ, do a Softmax to get ⍺ₖ ⱼ.</li></ul><h4>Training/Loss Calculation</h4><p>The alignment model directly computes a soft alignment — considers all inputs, which allows the gradient of the loss function — calculated for final outputs of the entire sequence to sequence model — to be back-propagated through. This gradient is used to train the alignment model as well as the whole translation model jointly.</p><p>Let ⍺ᵢ ⱼ be a probability that the target word Yᵢ is translated from a source word X<strong>ⱼ</strong> . Then, the <em>i</em>-th context vector Cᵢ is the expected annotation over all the annotations with probabilities ⍺ᵢ ⱼ . When loss at each time step is back-propagated, we calculate the gradient for all three inputs — previous hidden state, the previous output and the context vector. <em>(If this is a little confusing for you, please read more about back-propagation </em><a href="https://towardsdatascience.com/back-propagation-721bfcc94e34?source=friends_link&amp;sk=acbff34da1a05019364dff8893317331"><em>here</em></a><em>)</em> All the gradients flowing back in a time step shall be added together before we calculate the gradients for its inputs.</p><p>The gradient at each time step for Cₖ is used as the loss for the feed forward neural network we use to predict global alignment weights.</p><h3>Impact on Performance</h3><ul><li>The model with attention mechanism was able to outperform the conventional encoder–decoder model significantly, regardless of the sentence length and that it is much more robust to the length of a source sentence.</li><li>It was also able to correctly align each target word with the relevant words, or their annotations, in the source sentence as it generated a correct translation.</li><li>It enabled further development in the field by paving the road for <a href="https://towardsdatascience.com/transformers-89034557de14">Transformers</a> and SOTA models like <a href="https://medium.com/@ria.kulshrestha16/keeping-up-with-the-berts-5b7beb92766">Google’s BERT</a> — which inspired <a href="https://arxiv.org/pdf/1907.11692.pdf">RoBERTa</a> by Facebook, AzureML-BERT by Microsoft and many more.</li></ul><h3>Conclusion</h3><ol><li>In our current approach with RNNs, the intermediary state act as a bottleneck for performance.</li><li>Attention can solve this problem by looking at each individual input state while predicting next output hidden state.</li><li>The mathematics for calculating attention.</li><li>Integration with RNNs based models.</li><li>Performance of RNN + attention models.</li></ol><h4>Follow Up Read:</h4><ul><li><a href="https://towardsdatascience.com/transformers-89034557de14">Transformers</a></li><li><a href="https://towardsdatascience.com/keeping-up-with-the-berts-5b7beb92766">Keeping up with the BERTs</a></li></ul><p>If you liked this article and want to explore more about <a href="https://towardsdatascience.com/transformers-89034557de14">Transformer</a> and <a href="https://medium.com/@ria.kulshrestha16/keeping-up-with-the-berts-5b7beb92766">BERT</a> (out now), make sure to check out my articles on the same. 😄✌️</p><h3>References + Recommended Reads</h3><ul><li><a href="https://arxiv.org/pdf/1409.0473.pdf">Original Paper</a>.</li><li>I<a href="https://towardsdatascience.com/intuitive-understanding-of-attention-mechanism-in-deep-learning-6c9482aecf4f">ntuitive Understanding Of Attention Mechanism In Deep Learning</a> by Harshall Lamba.</li><li><a href="https://www.analyticsvidhya.com/blog/2019/11/comprehensive-guide-attention-mechanism-deep-learning/">A Comprehensive Guide to Attention Mechanism in Deep Learning for Everyone</a> by Analytics Vidhya.</li><li><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb</a> (TensorFlow Implementation available on their official website as a tutorial)</li></ul><h3>Other articles by me that I think you would enjoy😄</h3><ul><li><a href="https://towardsdatascience.com/back-propagation-721bfcc94e34">Yes, you should listen to Andrej Karpathy, and understand Back propagation</a></li><li><a href="https://towardsdatascience.com/evaluation-of-an-nlp-model-latest-benchmarks-90fd8ce6fae5">Evaluation of an NLP model — latest benchmarks</a></li><li><a href="https://towardsdatascience.com/machine-learning-in-computational-fluid-dynamics-7018941414b9">Machine Learning in Computational Fluid Dynamics</a></li><li><a href="https://medium.com/@ria.kulshrestha16/keeping-up-with-the-berts-5b7beb92766">Keeping Up With The BERTs</a> — to understand how BERT leveraged attention and created a bidirectional model.</li></ul><blockquote>I‘m glad you made it till the end of this article. <em>🎉<br></em>I hope your reading experience was as enriching as the one I had writing this.<em>💖</em></blockquote><blockquote>Do check out my other articles <a href="https://medium.com/@ria.kulshrestha16">here</a>. <em>🔍</em></blockquote><blockquote>If you want to reach out to me, my medium of choice would be <a href="https://twitter.com/ree_____ree">Twitter</a>. <em>📬</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a712f93bdb1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/attaining-attention-in-deep-learning-a712f93bdb1e">Understanding Attention In Deep Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>