<?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 Damodaran Selvaraj on Medium]]></title>
        <description><![CDATA[Stories by Damodaran Selvaraj on Medium]]></description>
        <link>https://medium.com/@damodaran.selvaraj?source=rss-b50764aaf4a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aOeDJvt_mevP5XzB</url>
            <title>Stories by Damodaran Selvaraj on Medium</title>
            <link>https://medium.com/@damodaran.selvaraj?source=rss-b50764aaf4a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:45:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@damodaran.selvaraj/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[RAG Demystified — Part 1: Why LLMs Fail (And How RAG Fixes It)]]></title>
            <link>https://medium.com/@damodaran.selvaraj/rag-demystified-part-1-why-llms-fail-and-how-rag-fixes-it-ff683fada15d?source=rss-b50764aaf4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff683fada15d</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Damodaran Selvaraj]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 14:17:22 GMT</pubDate>
            <atom:updated>2026-07-26T14:17:22.210Z</atom:updated>
            <content:encoded><![CDATA[<h4>Before we build anything, we need to understand what is broken — and why</h4><blockquote><strong>LLMs can write. RAG makes them right.</strong></blockquote><p>If you have ever asked ChatGPT something and gotten a confident, well-written, completely wrong answer if so you have already met the problem this series is about.</p><p>Large Language Models are remarkable. They can write code, summarize documents, explain complex ideas, and hold a conversation. But underneath all of that fluency is a fundamental limitation that does not go away no matter how large the model gets.</p><blockquote><strong>They are working from memory. And memory has limits.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vfg6tezk2_hmW6A4YcfjBA.png" /><figcaption>AI generated Image</figcaption></figure><h3>The Closed Book Problem</h3><p>Think about two kinds of exam students.</p><p>The first student memorized the entire textbook before the exam. They can answer anything covered in that book — fast, fluently, confidently. But if you ask something outside those pages, they either guess or make something up. They will never say “I don’t know.” That feels like failure to them.</p><p>The second student walks in with the textbook open on the desk. They do not need to memorize everything. When a question comes, they look it up, read the relevant section, and then answer.</p><blockquote><strong>An LLM is the first student.</strong></blockquote><p>Every answer comes from what it absorbed during training billions of parameters, frozen in place the moment training ended. Researchers call this parametric memory. It is powerful.</p><p>It is also brittle in three very specific ways.</p><h3>Failure Mode 1 — Hallucination</h3><blockquote>“The model generates fluent, confident, completely false answers.”</blockquote><p>Here is the uncomfortable truth about how LLMs work. They are next-token prediction machines. They are trained to produce text that sounds correct, not text that is verified against facts.</p><p>So when you ask about something the model was never taught or something it only partially learned, it does not stop and say “I’m not sure.” It fills the gap with the most statistically plausible continuation.</p><p><strong>Example:</strong><br>Ask an LLM about a niche legal case, an obscure research paper, or a local regulation it has never seen. It will often return a perfectly structured, confidently written answer with case numbers, author names, and citations are all invented.</p><blockquote><strong>Why does hallucination happen? Because LLMs are next‑token predictors, not truth engines.</strong></blockquote><h3>Failure Mode 2 — Knowledge Cutoff</h3><blockquote>“The model’s world ends on the day training ended.”</blockquote><p>Every LLM has a training cutoff date. Everything after that date is invisible to it. The model is not being evasive it genuinely cannot know what it was never shown.</p><p><strong>Example:</strong></p><pre>You:   Who won the 2026 FIFA World Cup?<br><br>LLM:   [Trained before 2026]<br>       It will either say it doesn&#39;t know,<br>       or worse - it will guess and present<br>       that guess as fact.</pre><p>Now imagine asking about last quarter’s earnings, a regulation passed three months ago, or a product your company launched last week. The model has no access to any of it.</p><h3>Failure Mode 3 — Private Data Blindness</h3><blockquote>“The model has never seen your data. Not even once.”</blockquote><p>This is the failure mode that hits every company trying to use AI internally.</p><p><strong>Example:</strong></p><p>You work at an insurance company. Your organization has thousands of internal policy documents, claims procedures, HR handbooks, and product guidelines. None of that ever appeared on the public internet. None of it was in the training data.</p><pre>You:   What is our internal escalation process for disputed claims <br>       over $50,000?<br><br>LLM:   No idea.<br>       It was never trained on your documents.<br>       It cannot answer this question.</pre><p>You could ask the world’s most powerful LLM and it would still faill, it is not because the model is weak, but because the information was never in its memory.</p><blockquote>The model is a closed book.</blockquote><h3>The fix: RAG makes it an Open Book</h3><p>Open‑book exams let you consult the right pages when you answer. RAG does that for LLMs: it retrieves relevant documents from your corpus and injects them into the prompt at inference time. The model now writes with evidence.</p><blockquote><strong>The model no longer guesses. It reads first. Then it answers. It is Open Book.</strong></blockquote><p>The model now writes with evidence.</p><ul><li><strong>Groundedness</strong> — Answers come from retrieved passages, not just memory.</li><li><strong>Freshness</strong> — New documents are available immediately; no retraining needed.</li><li><strong>Traceability </strong>— You can cite sources for every claim.</li></ul><h3>So what exactly is RAG?</h3><blockquote><strong>RAG stands for Retrieval‑Augmented Generation.</strong></blockquote><p>Break it down:<br><strong>Retrieval —</strong> Find the right information from your documents.<br><strong>Augmented —</strong> Add that information to the prompt.<br><strong>Generation — </strong>Generate the answer using both the retrieved content and the model’s reasoning.</p><h3>Why this matters in practice?</h3><ul><li>Your model stops guessing and starts citing.</li><li>You can ship updates by updating documents — not retraining models.</li><li>You unlock private knowledge (wikis, PDFs, emails, contracts) safely, with source attributions.</li><li>facts at runtime.</li><li>Not a silver bullet. If retrieval brings the wrong passages, generation won’t save you. Garbage in → Garbage out still applies.</li></ul><h3>Where we’re headed next</h3><p>In Part 2, we’ll map the full pipeline — from documents to answers — so you can see exactly where to invest: Ingestion &amp; Parsing → Chunking → Embeddings → Vector Database → Retrieval → Prompting → LLM.</p><blockquote>RAG doesn’t make LLMs smarter.<br>It makes them informed.<br>And that simple shift changes everything.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff683fada15d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Three AI Settings Every Beginner Should Know: Temperature, Top-K, and Top-P]]></title>
            <link>https://medium.com/@damodaran.selvaraj/the-three-ai-settings-every-beginner-should-know-temperature-top-k-and-top-p-explained-simply-2714e4de2479?source=rss-b50764aaf4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2714e4de2479</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[topps]]></category>
            <category><![CDATA[top-k]]></category>
            <category><![CDATA[temperature]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Damodaran Selvaraj]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 18:28:48 GMT</pubDate>
            <atom:updated>2026-07-12T18:30:32.866Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ever wondered why ChatGPT gives a different answer to the same question? That’s not a bug. The secret isn’t magic. It’s a design choice and it’s controlled by three settings: <strong>temperature, top-k, and top-p.</strong></h4><p>If you’ve started using AI models through ChatGPT, an API, or tools like Ollama, you’ve probably seen settings called <strong>temperature, top-k and top-p.</strong></p><p>They’re just <strong>three knobs that control how the AI chooses its next word</strong>.</p><p>Once you understand these settings, you’ll know how to make AI more factual, more creative, or somewhere in between.</p><h3>Three Settings in One Sentence</h3><p>Before going deeper, here’s the simplest definition of each parameter.</p><ul><li><strong>Temperature:</strong> Controls <strong>how random or predictable </strong>the AI is when choosing the next word.</li><li><strong>Top-K:</strong> Limits the model to choosing from <strong>only the top K most likely words</strong>.</li><li><strong>Top-P (Nucleus Sampling):</strong> Lets the model choose from the <strong>smallest group of words whose combined probability reaches P%</strong>.</li></ul><p>Think of these as <strong>filters</strong> that influence how the AI picks its next word.</p><blockquote><strong><em>Note:</em></strong><em> </em>Exact parameter names, ranges, and behavior can vary slightly depending on the AI provider or library, but the underlying ideas are very similar.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Newa3_J0B95xY-FXA2f8cg.png" /><figcaption>AI generated Image</figcaption></figure><h3>Why Do AI Responses Change?</h3><p>Every time an AI writes a sentence, it <strong>is not</strong> pulling words from memory like a person. Instead, it predicts:</p><blockquote><strong><em>“Given everything written so far, what word should come next?”</em></strong></blockquote><p>For every next word, the model considers many possibilities. After writing:</p><blockquote><strong><em>The cat sat on the…</em></strong></blockquote><p>The AI might think:</p><ul><li>mat</li><li>floor</li><li>chair</li><li>sofa</li><li>windowsill</li></ul><p>Some guesses are more natural than others.</p><p>AI predicts the <strong>most likely next word</strong>, then repeats that process one word at a time until the response is complete. At every step, there are many possible words it could choose. The sampling settings decide <strong>which of those words are allowed</strong> and <strong>how adventurous the model should be</strong>.</p><h3>Temperature: The Randomness Knob</h3><p><strong>Temperature controls how adventurous the AI becomes when choosing its next word.</strong></p><p>A low temperature makes the AI play it safe.</p><p>A high temperature encourages it to take more risks.</p><p>It doesn’t change what the AI knows. It changes <strong>how boldly it uses that knowledge.</strong></p><h4>Imagine a Careful Student vs an Imaginative Writer</h4><p>Think of temperature like this:</p><ul><li><strong>Low temperature:</strong> A careful student answering exam questions.</li><li><strong>Medium temperature:</strong> A friendly coworker sharing ideas.</li><li><strong>High temperature:</strong> A creative novelist brainstorming wild concepts.</li></ul><p>A higher temperature doesn’t make the model more knowledgeable. It simply makes it more willing to choose lower-probability tokens.</p><h4>Typical Temperature Range</h4><p>Typical range:</p><ul><li><strong>0.0–0.3</strong> → very predictable</li><li><strong>0.7–0.8</strong> → balanced</li><li><strong>1.5–2.0</strong> → highly creative (if supported)</li></ul><h3>Same Prompt, Different Temperatures</h3><h4>Low Temperature (0.0–0.3)</h4><p>The AI almost always chooses the safest next word.</p><p>Example prompt:</p><blockquote>Explain what a database is.</blockquote><p>Output:</p><blockquote>A database is an organized collection of data used to store and retrieve information efficiently.</blockquote><p>Clear. Reliable. Not very imaginative.</p><p>Great for:</p><ul><li>Summaries</li><li>Documentation</li><li>Customer support</li><li>Technical writing</li><li>Code generation</li></ul><h4>Medium Temperature (0.7–0.8)</h4><p>This is the sweet spot for many applications. The AI still stays accurate but writes more naturally.</p><p>Example:</p><blockquote>A database is like a digital filing cabinet that stores information in an organized way, making it easy to search and update.</blockquote><p>Still correct. More conversational.</p><p>Ideal for:</p><ul><li>Blog writing</li><li>Emails</li><li>Marketing copy</li><li>General conversations</li></ul><h4>High Temperature (1.5–2.0)</h4><p>Now the AI explores unusual wording.</p><p>Example:</p><blockquote>Imagine a magical librarian who remembers every fact you’ve ever stored and instantly finds it when you ask.</blockquote><p>Much more creative. Sometimes brilliant. Sometimes a little strange.</p><p>Best for:</p><ul><li>Brainstorming</li><li>Stories</li><li>Marketing ideas</li><li>Poetry</li></ul><p>Not ideal for precise factual answers.</p><h3>Top-K: Limit the Choices</h3><p>Instead of considering every possible next word, the AI first keeps only the <strong>K most likely choices</strong>. The model then samples from those remaining words according to their probabilities.</p><p>Imagine you’re ordering lunch. Normally the restaurant has <strong>200 dishes</strong>. Now imagine someone hands you a menu showing only the <strong>Top 10 most popular dishes</strong>. You’ll probably still enjoy your meal — but your choices are more limited. <strong>That’s exactly what Top-K does.</strong></p><p>It says:</p><blockquote>“Only consider the K most likely words.”</blockquote><h4>Example</h4><p>Suppose the AI predicts:</p><ol><li>morning</li><li>day</li><li>afternoon</li><li>evening</li><li>weekend</li><li>holiday</li><li>season</li></ol><p>If <strong>Top-K = 5, </strong>The AI can only choose from the first five words. The remaining words are discarded.</p><p>If <strong>Top-K = 50, </strong>many more possibilities become available. The writing becomes more varied.</p><h4>When Top-K Helps</h4><p>Good for:</p><ul><li>Preventing strange word choices</li><li>Keeping responses focused</li><li>Slightly increasing consistency</li></ul><h4>When It Hurts</h4><p>If K is too small, responses become repetitive. The model may keep using nearly identical wording.</p><h3>Top-P (Nucleus Sampling): Choose Until the Basket Is Full</h3><p>Top-p is called nucleus sampling because the retained words form the “core” (or nucleus) of the probability distribution.</p><p>Top-P is more flexible than Top-K. Instead of saying: <strong>“Always keep exactly 50 words.” </strong>It says:</p><blockquote><strong>“Keep adding the most likely words until their combined probability reaches P%.”</strong></blockquote><p>The AI keeps adding the most likely words until their combined likelihood reaches <strong>P</strong>.</p><p>For example:</p><ul><li>morning — 40%</li><li>day — 25%</li><li>afternoon — 10%</li><li>evening — 8%</li><li>weekend — 5%</li><li>others — 12%</li></ul><p><strong>If Top-P = 0.80, </strong>The AI keeps:</p><ul><li>morning</li><li>day</li><li>afternoon</li><li>evening</li></ul><p>because together they cover about 83% of the total likelihood. Everything else is ignored.</p><blockquote>The model still samples randomly from the remaining tokens. It does NOT automatically pick the highest probability token.</blockquote><h3>Why Top-P Often Works Better</h3><p>Unlike Top-K, Top-P adapts automatically. Sometimes only three words are good enough. Sometimes twenty words deserve consideration. Top-P adjusts to the situation.</p><p>That’s why many modern AI systems prefer Top-P over Top-K.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwwXOEtCMoD7gsvE21fiDg.png" /><figcaption>AI generated Image</figcaption></figure><h3>More Technical — What Actually Happens Inside the Model?</h3><p>So far, we’ve said that the model “predicts the next word.” But what does that actually mean inside a Large Language Model (LLM)?</p><p>After the transformer finishes processing your prompt, the <strong>final transformer layer</strong> produces a numerical representation called the <strong>hidden state</strong> (also known as the hidden representation) for the next token. This representation is then passed to the <strong>Language Modeling Head (LM Head), </strong>a simple linear layer whose output size matches the model’s entire vocabulary.</p><p>If the vocabulary contains <strong>100,000 tokens</strong>, the LM Head produces <strong>100,000 numbers</strong>, one for each possible token. These numbers are called <strong>logits</strong>. A logit is <strong>not</strong> a probability; it is simply the model’s raw confidence score for each token. Higher logits indicate that the model believes a token is more likely to come next.</p><p>For example, after the prompt:</p><blockquote><strong><em>“The capital of France is”</em></strong></blockquote><p>the model might produce logits like this (illustrative values):</p><ul><li>Paris — 8.2</li><li>London — 3.1</li><li>Berlin — 2.9</li><li>Apple — 0.8</li><li>Elephant — 2.4</li></ul><p>These numbers are difficult to interpret directly because they are not probabilities. To convert them into probabilities, the model applies a function called <strong>Softmax</strong>.</p><p>Why doesn’t the LM Head produce probabilities directly instead of logits?</p><blockquote><strong>Neural networks naturally produce arbitrary real-valued scores (logits). Softmax converts those scores into a valid probability distribution.</strong></blockquote><h4>Softmax: Turning Scores into Probabilities</h4><p>Softmax converts the logits into a probability distribution.</p><p>After Softmax:</p><ul><li>Every vocabulary token receives a probability.</li><li>All probabilities are between <strong>0 and 1</strong>.</li><li>The probabilities always add up to <strong>1 (100%)</strong>.</li></ul><p>The result might look like this:</p><ul><li>Paris — 94.8%</li><li>London — 2.6%</li><li>Berlin — 2.1%</li><li>Apple — 0.3%</li><li>Elephant — 0.2%</li></ul><p>Notice that every token still has a probability, even though most are extremely small. At this point, the model hasn’t picked the next token yet, it has only calculated how likely every token is.</p><p>This probability distribution is where <strong>Temperature</strong>, <strong>Top-K</strong>, and <strong>Top-P</strong> begin to influence text generation.</p><h4>Temperature: Reshaping the Probability Distribution</h4><p>Temperature is applied <strong>before Softmax</strong> by dividing every logit by a temperature value (<strong>T</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*fdWEXm7qK2F5-BHP39JTkg.png" /></figure><ul><li><strong>T = 1</strong> → Nothing changes. The model uses its original confidence scores.</li><li><strong>T &lt; 1</strong> (for example, <strong>0.5</strong>) → The probability distribution becomes <strong>sharper</strong>. High-probability tokens become even more likely, while low-probability tokens become even less likely. The output becomes more predictable and deterministic.</li><li><strong>T &gt; 1</strong> (for example, <strong>1.5</strong>) → The probability distribution becomes <strong>flatter</strong>. Lower-probability tokens receive a better chance of being selected, making the output more diverse and creative.</li></ul><p>One important point is that <strong>temperature never removes any tokens</strong>. Every token remains available, it only changes their relative probabilities.</p><h4>Top-K: Keeping Only the K Best Candidates</h4><p>After the probabilities have been calculated, <strong>Top-K</strong> applies a filter.</p><p>First, all vocabulary tokens are sorted from the highest probability to the lowest. Then the model keeps only the <strong>K most probable tokens</strong> and discards the rest.</p><p>For example, imagine the vocabulary contains <strong>100,000 tokens</strong>.</p><p>If <strong>Top-K = 50, </strong>the model keeps only the <strong>50 most likely tokens</strong>.</p><p>Every other token immediately receives a probability of <strong>zero</strong>.</p><p>Finally, the remaining probabilities are normalized again so that they still add up to 100%, and the next token is sampled only from these 50 candidates.</p><p>Top-K therefore answers a simple question:</p><blockquote><strong><em>“Out of the entire vocabulary, how many candidate words should the model even consider?”</em></strong></blockquote><p>A smaller K produces safer and more repetitive outputs, while a larger K allows more variety.</p><h4>Top-P (Nucleus Sampling): Keep Enough Tokens to Reach P%</h4><p>Top-P takes a different approach. Instead of keeping a fixed number of tokens, it keeps the <strong>smallest set of tokens whose combined probability reaches a threshold P</strong>.</p><p>Suppose the sorted probabilities look like this:</p><ul><li>Paris — 60%</li><li>London —18%</li><li>Berlin — 12%</li><li>Rome — 6%</li><li>Madrid — 2%</li><li>Others — 2%</li></ul><p>If <strong>Top-P = 0.90, </strong>the model keeps adding tokens until the cumulative probability reaches <strong>90%</strong>.</p><p>It would therefore keep:</p><ul><li>Paris</li><li>London</li><li>Berlin</li></ul><p>because together they already account for <strong>90%</strong> of the total probability. Everything else is discarded, and the remaining probabilities are normalized before sampling.</p><p>Unlike Top-K, the number of retained tokens changes dynamically.</p><ul><li>When the model is very confident, only a few tokens may be kept.</li><li>When many tokens have similar probabilities, dozens or even hundreds of tokens might be retained.</li></ul><p>This adaptability is why <strong>Top-P is widely preferred in modern language models</strong>.</p><blockquote><strong>Even after Temperature, Top-K, and Top-P have narrowed the choices, the model usually doesn’t simply pick the highest-probability token. Instead, it randomly samples from the remaining candidates according to their probabilities. Higher-probability tokens are still much more likely to be selected, but lower-probability tokens can occasionally be chosen. This randomness is what makes repeated prompts produce different outputs.</strong></blockquote><h3>Python Example</h3><p>Here’s what these settings might look like in an API call:</p><pre>from openai import OpenAI</pre><pre>client = OpenAI()<br>response = client.responses.create(<br>    model=&quot;gpt-4.1&quot;,<br>    input=&quot;Explain what a database is.&quot;,<br>    temperature=0.7,<br>    top_p=0.9<br>)<br>print(response.output_text)</pre><p>Some providers also expose a top_k parameter, while others do not.</p><h4>Putting It All Together</h4><p>The complete text-generation pipeline looks like this:</p><blockquote><strong>Transformer → Hidden State → LM Head → Logits → Temperature scaling → Softmax → Top-K/Top-P filtering </strong>→ Renormalize probabilities <strong>→ Sample Next Token (Randomly) → Repeat</strong></blockquote><p>This entire process happens <strong>for every single generated token</strong>, often hundreds of times while producing one response.</p><p>Once you understand this pipeline, the three sampling parameters become much easier to reason about:</p><ul><li><strong>Temperature</strong> reshapes the probability distribution.</li><li><strong>Top-K</strong> keeps only the K highest-probability candidates.</li><li><strong>Top-P</strong> keeps the smallest set of candidates whose cumulative probability reaches P%.</li><li>Finally, the model randomly samples one token from the remaining candidates and repeats the process until the response is complete.</li></ul><h3>Final Thoughts</h3><p>You don’t need to memorize complicated probability theory to use these settings effectively.</p><p>Just remember:</p><ul><li><strong>Temperature controls how adventurous the AI is.</strong></li><li><strong>Top-K limits how many choices are available.</strong></li><li><strong>Top-P adapts the available choices based on probability.</strong></li></ul><p>Start with sensible defaults, experiment one setting at a time, and see how the outputs change. After a few experiments, these “mysterious AI knobs” will feel much less mysterious.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2714e4de2479" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Byte Pair Encoding (BPE) Explained Simply: How AI Turns Words into Tokens]]></title>
            <link>https://medium.com/@damodaran.selvaraj/byte-pair-encoding-bpe-explained-simply-how-ai-turns-words-into-tokens-5ec52cc7f39c?source=rss-b50764aaf4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ec52cc7f39c</guid>
            <category><![CDATA[tokenizer]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[byte-pair-encoding]]></category>
            <dc:creator><![CDATA[Damodaran Selvaraj]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 18:07:18 GMT</pubDate>
            <atom:updated>2026-07-07T18:07:18.480Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn <strong>Byte Pair Encoding (BPE)</strong>, <strong>AI tokenization</strong>, and <strong>how large language models tokenize text</strong> with simple examples, Python code, and step-by-step explanations.</h4><p>Have you ever wondered how AI understands your sentences?</p><p>When you type:</p><blockquote><strong><em>“I love learning AI.”</em></strong></blockquote><p>Does AI read it like we do? Not exactly.</p><p>Every prompt you type into ChatGPT goes through tokenization before the model can understand it. AI first breaks your text into smaller pieces called <strong>tokens</strong>. A token is the basic unit of text that an AI model processes. A token may be an entire word, part of a word, a punctuation mark, or even a single character.But how does AI decide where to split words? That is where <strong>Byte Pair Encoding (BPE)</strong> comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5d--92PppHkUfHOTuOAu4A.png" /><figcaption>AI generated Image</figcaption></figure><h3>What is Byte Pair Encoding (BPE)?</h3><p><strong>Byte Pair Encoding (BPE)</strong> is a method that teaches AI how to split text into useful pieces called <strong>tokens</strong>.</p><p>Think of it as teaching AI a dictionary. Instead of memorizing every possible word, AI learns the most common pieces of words. This makes learning much easier.</p><p>Suppose you often write:</p><ul><li>playing</li><li>player</li><li>played</li><li>plays</li></ul><p>Instead of learning all four words separately, AI learns:</p><ul><li>play</li><li>ing</li><li>er</li><li>ed</li><li>s</li></ul><p>Now AI can build many words from just a few pieces. Just like LEGO blocks build many different toys, BPE builds many different words.</p><h3>Why Do AI Models Need BPE?</h3><p>Imagine a dictionary with every English word.</p><p>Now add:</p><ul><li>names</li><li>slang</li><li>emojis</li><li>spelling mistakes</li><li>programming languages</li></ul><p>The dictionary becomes enormous.</p><p>Instead, AI learns smaller word pieces. This reduces memory. It also helps AI understand new words it has never seen before. Traditional word-based tokenizers often struggle with unseen words, known as the <strong>Out-of-Vocabulary (OOV) problem</strong>. BPE greatly reduces this issue by breaking unfamiliar words into smaller known pieces.</p><p>For example:</p><pre>unbelievably</pre><p>AI may split it into</p><pre>un<br>believe<br>ably</pre><p>Even if it never saw the complete word before.</p><h3>Real-Life Analogy</h3><p>Imagine you own a toy shop.</p><p>Would you store every possible LEGO castle?</p><p>No. You only store LEGO bricks. Then you build anything you need.</p><p>BPE works the same way. Instead of storing every word, it stores useful word pieces.</p><h3>How Does Byte Pair Encoding (BPE) Work?</h3><p>Let’s understand the process.</p><p>Suppose our training data contains these words.</p><pre>low<br>lower<br>lowest<br>low<br>low</pre><h4>Step 1: Split Every Word Into Characters</h4><p>Initially, BPE treats every character separately.</p><pre>l o w</pre><pre>l o w e r</pre><pre>l o w e s t</pre><p>Characters become the first tokens.</p><h4>Step 2: Count Adjacent Character Pairs</h4><p>An <strong>adjacent pair</strong> means two neighboring characters.</p><p>For example</p><pre>l o<br>o w<br>w e<br>e r</pre><p>Now count how often every pair appears.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*nYBEElgnhBFhVYqhlOGw3g.png" /></figure><p>The pair</p><pre>l o</pre><p>appears most often.</p><h4>Step 3: Merge the Most Common Pair</h4><p>Now merge</p><pre>l + o<br><br>into<br><br>lo</pre><p>The words become</p><pre>lo w<br><br>lo w e r<br>lo w e s t</pre><h4>Step 4: Repeat Again</h4><p>Now count pairs again.</p><p>Perhaps</p><pre>lo w</pre><p>is the most common. Merge it.</p><p>Now we get</p><pre>low<br>low er<br>low est</pre><p>Continue repeating.</p><blockquote><strong>The tokenizer continues merging until it reaches a predefined vocabulary size (for example, 50,000 or 100,000 tokens). These learned tokens become the tokenizer’s vocabulary.</strong></blockquote><p>Eventually AI learns tokens like</p><ul><li>low</li><li>er</li><li>est</li></ul><p>instead of individual letters. This process is called <strong>Byte Pair Encoding</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCoNtxs9Fj8pkhtHiyd-_A.png" /><figcaption>AI generated Image</figcaption></figure><h3>BPE vs Word Tokenization: Key Differences</h3><p><strong>Word tokenization</strong> means splitting text into complete words.</p><p>Example</p><pre>I love AI</pre><p>becomes</p><pre>I<br>love<br>AI</pre><p>BPE works differently. It splits words into meaningful pieces.</p><p>Example</p><pre>unbelievable</pre><p>may become</p><pre>un<br>believe<br>able</pre><p><strong>Word Tokenization —</strong> Splits by spaces, Large vocabulary, Cannot handle unknown words well.</p><p><strong>BPE —</strong> Learns useful word pieces, Smaller vocabulary, Handles unknown words much better</p><h3>Why GPT Uses BPE</h3><p>Large language models process billions of words. Learning every word is impossible. Instead, GPT learns reusable pieces.</p><p>That helps it</p><ul><li>understand new words</li><li>reduce vocabulary size</li><li>reduce memory usage</li><li>process text efficiently</li></ul><p>That is why tokenization is one of the first steps before AI starts predicting text.</p><h4>Common Byte Pair Encoding (BPE) Mistakes Beginners Make</h4><h4>Mistake 1</h4><p>Thinking BPE stores whole words. It usually stores smaller pieces.</p><h4>Mistake 2</h4><p>Thinking tokens always equal words. One word can become many tokens.</p><h4>Mistake 3</h4><p>Thinking BPE understands meaning. It does not. It only learns frequent text patterns. The language model later learns meaning from those patterns.</p><h4>Mistake 4</h4><p>Thinking every AI model uses the same tokenizer. Different AI models often use different tokenization methods.</p><h3>Frequently Asked Questions</h3><h4>What is Byte Pair Encoding?</h4><p>It is an algorithm that learns common character or word-piece combinations and turns them into tokens.</p><h4>Why does GPT use Byte Pair Encoding?</h4><p>It reduces vocabulary size while handling unseen words efficiently.</p><h4>Is one token always one word?</h4><p>No. A single word may become several tokens.</p><h4>Is BPE difficult?</h4><p>Not at all. Once you understand repeated merging, the idea becomes very simple.</p><h3>Key Takeaways</h3><p>You learned that:</p><ul><li>Byte Pair Encoding (BPE) breaks text into useful tokens.</li><li>A token is a small piece of text.</li><li>BPE repeatedly merges the most common neighboring characters.</li><li>AI learns reusable word pieces instead of every possible word.</li><li>GPT uses BPE because it saves memory and handles new words well.</li></ul><h3>Final Thoughts</h3><p>At first, Byte Pair Encoding may sound complicated.</p><p>In reality, it follows one simple idea.</p><p>Find the most common neighboring characters. Merge the most frequent pair into a new token. Repeat.</p><p>That simple process powers the tokenization used by many modern AI systems.</p><p>Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ec52cc7f39c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner-Friendly Guide to DSPy]]></title>
            <link>https://medium.com/@damodaran.selvaraj/a-beginner-friendly-guide-to-dspy-7579c432e2fe?source=rss-b50764aaf4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7579c432e2fe</guid>
            <category><![CDATA[dspy]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai-prompting]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Damodaran Selvaraj]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 18:25:30 GMT</pubDate>
            <atom:updated>2026-07-06T18:25:30.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8I4xfKR7kObEPmOXrRKGg.png" /><figcaption>Image Source : <a href="https://github.com/stanfordnlp/dspy">https://github.com/stanfordnlp/dspy</a></figcaption></figure><h4>Introduction</h4><p>If you’ve worked with Large Language Models (LLMs), you’ve probably done this:</p><pre>prompt = &quot;Summarize this text in 3 bullet points&quot;<br>response = llm(prompt)</pre><p>And then…</p><ul><li>You tweak the prompt</li><li>You try different wording</li><li>You repeat this again and again</li></ul><p>This process is called <strong>prompt engineering</strong>, and it quickly becomes messy, fragile, and hard to scale.</p><h4>What if instead of writing prompts… you could program behavior?</h4><p>That’s exactly what <strong>DSPy (Declarative Self-improving Python)</strong> enables.</p><p>This guide will teach you DSPy step-by-step, from <strong>basic concepts to optimizers</strong>, in a way that builds intuition first and code second.</p><h4>What DSPy Solves?</h4><p>DSPy transforms prompting from manual string crafting into programming with learnable components.</p><p>Instead of writing prompts, you:</p><ol><li>Define what you want (using Signatures)</li><li>Compose operations (using Modules)</li><li>Let the system optimize (using Optimizers)</li></ol><p>Think of it like this:</p><ul><li>Traditional prompting = writing HTML by hand in Notepad</li><li>DSPy = using React with a compiler that optimizes your code</li></ul><h3>1. What is DSPy?</h3><p>DSPy is a framework for building LLM applications <strong>without manually writing prompts</strong>.</p><p>Instead of telling the model <em>how</em> to respond, you define:</p><ul><li>what inputs you have</li><li>what outputs you want</li></ul><p>And DSPy figures out the rest.</p><h4>Mental Model</h4><p>Think of DSPy like this:</p><pre>You → Define task<br>DSPy → Builds prompt<br>LLM → Executes<br>DSPy → Improves over time</pre><h3>2. Why DSPy?</h3><h4>Traditional Approach Problems</h4><ul><li>Prompts are hard to maintain</li><li>Small wording changes break results</li><li>No structured outputs</li><li>No systematic way to improve</li></ul><h4>DSPy Approach</h4><ul><li>Structured input/output</li><li>Reusable components</li><li>Composable pipelines</li><li>Automatic optimization</li></ul><h3>3. Core Concept: Signature</h3><p>The most important concept in DSPy is the <strong>Signature</strong>.</p><h4>What is a Signature?</h4><p>A <strong>Signature defines the shape of a task</strong>.</p><pre>import dspy<br><br>class Summarize(dspy.Signature):<br>    &quot;&quot;&quot;Summarize the text in 2 lines&quot;&quot;&quot;<br>    <br>    text = dspy.InputField()<br>    summary = dspy.OutputField()</pre><h4>Think of it like an API</h4><pre>Input:<br>    text<br><br>Output:<br>    summary</pre><h4>Important Notes</h4><ul><li>text, summary are <strong>not keywords</strong></li><li>You can rename them</li><li>But meaningful names help the LLM</li></ul><p><strong>Bad Naming</strong></p><pre>a = dspy.InputField()<br>b = dspy.OutputField()</pre><p><strong>Good Naming</strong></p><pre>question = dspy.InputField()<br>answer = dspy.OutputField()</pre><p><strong>Role of Docstring</strong></p><pre>&quot;&quot;&quot;Summarize the text in 2 lines&quot;&quot;&quot;</pre><p>This is NOT just a comment. DSPy reads this and uses it as <strong>instruction.</strong></p><h3>4. From Signature to Execution</h3><p>To actually run a Signature, we use <strong>Modules like Predict.</strong></p><p><strong>Example</strong></p><pre>summarizer = dspy.Predict(Summarize)<br><br>result = summarizer(text=&quot;DSPy simplifies LLM development.&quot;)<br>print(result.summary)</pre><p>What happens internally?</p><pre>[Docstring] → instruction<br>[InputField] → input<br>[OutputField] → expected output</pre><p>DSPy builds a prompt automatically.</p><h3>5. Types of DSPy Modules (How Tasks Are Executed)</h3><p>So far, you’ve learned:</p><ul><li><strong>Signature</strong> → defines <em>what</em> the task is</li><li>Now we learn <strong>Modules</strong> → define <em>how</em> the task is executed</li></ul><h4>Big Picture</h4><p>You can use the <strong>same Signature</strong> with different Modules:</p><pre>class QA(dspy.Signature):<br>    &quot;&quot;&quot;Answer the question clearly&quot;&quot;&quot;<br>    <br>    question = dspy.InputField()<br>    answer = dspy.OutputField()</pre><p>Now you can execute this in different ways:</p><pre>qa1 = dspy.Predict(QA)<br>qa2 = dspy.ChainOfThought(QA)<br>qa3 = dspy.ReAct(QA)</pre><p>Same task, different behavior.</p><p><strong>Mental Model</strong></p><pre>Signature = WHAT to do<br>Module   = HOW to do it</pre><h4>5.1 Predict (Basic Execution)</h4><p><strong>What it does:</strong></p><p>Gives a <strong>direct answer</strong> without reasoning.</p><pre>qa = dspy.Predict(QA)</pre><p>When to use:</p><ul><li>summarization</li><li>classification</li><li>extraction</li><li>simple generation</li></ul><p>Example:</p><pre>result = qa(question=&quot;What is AI?&quot;)<br>print(result.answer)</pre><p>Think of it as:</p><blockquote><em>“Just give me the answer”</em></blockquote><h4>5.2 ChainOfThought (CoT)</h4><p>What it does:</p><p>Encourages the model to <strong>think step-by-step before answering</strong></p><pre>qa = dspy.ChainOfThought(QA)</pre><p>Example behavior:</p><pre>Step 1: Understand the question<br>Step 2: Apply logic<br>Step 3: Give final answer</pre><p>When to use:</p><ul><li>math problems</li><li>logical reasoning</li><li>complex QA</li></ul><p>Think of it as:</p><blockquote><em>“Think first, then answer”</em></blockquote><h4>5.3 ProgramOfThought (PoT)</h4><p>What it does:</p><p>Breaks a problem into <strong>intermediate steps or variables</strong>, like writing a small program.</p><pre>qa = dspy.ProgramOfThought(QA)</pre><p>Example behavior:</p><pre>Let x = 25 * 10<br>Let y = 25 * 2<br>Answer = x + y = 300</pre><p>When to use:</p><ul><li>structured reasoning</li><li>multi-step calculations</li><li>problems that benefit from decomposition</li></ul><p>Think of it as:</p><blockquote><em>“Write a mini program to solve the problem”</em></blockquote><h4>5.4 ReAct (Reason + Act)</h4><p>What it does:</p><p>Combines <strong>reasoning + taking actions (like using tools)</strong></p><pre>qa = dspy.ReAct(QA)</pre><p>Behavior:</p><pre>Thought → Action → Observation → Repeat → Answer</pre><p>Example:</p><pre>Thought: I need more info<br>Action: Search database<br>Observation: Found relevant data<br>Answer: Final response</pre><p>When to use:</p><ul><li>agents</li><li>tool usage (APIs, search, database)</li><li>multi-step workflows</li></ul><p>Think of it as:</p><blockquote><em>“Think, act, observe, repeat”</em></blockquote><h4>5.5 MultiChainComparison</h4><p>What it does:</p><ul><li>Generates <strong>multiple answers</strong></li><li>Compares them</li><li>Picks the best one</li></ul><pre>qa = dspy.MultiChainComparison(QA)</pre><p>Behavior:</p><pre>Answer 1 → Candidate<br>Answer 2 → Candidate<br>Answer 3 → Candidate<br>↓<br>Select best answer</pre><p>When to use:</p><ul><li>high-quality generation</li><li>ambiguous tasks</li><li>when correctness matters</li></ul><p>Think of it as:</p><blockquote><em>“Ask multiple experts, choose the best answer”</em></blockquote><h4>5.6 Retrieve</h4><p>What it does:</p><p>Retrieves <strong>relevant information from external data sources.</strong></p><pre>retriever = dspy.Retrieve(k=3)</pre><p>Behavior:</p><pre>Query → Search documents → Return top-k relevant results</pre><p>Example:</p><pre>docs = retriever(&quot;What is DSPy?&quot;)</pre><p>When to use:</p><ul><li>RAG (Retrieval-Augmented Generation)</li><li>knowledge-based systems</li><li>document search</li></ul><p>Think of it as:</p><blockquote><em>“Find relevant information before answering”</em></blockquote><h3>Final Insight</h3><p>All these modules work on the <strong>same Signature</strong>, but change how the LLM behaves.</p><pre>Same task → Different thinking strategies → Different results</pre><h4>Practical Rule</h4><pre>Start with Predict  <br>If accuracy is low → try ChainOfThought  <br>If still not enough → use advanced modules</pre><p>This flexibility is what makes DSPy powerful — you are not just calling an LLM, you are <strong>designing how it thinks</strong>.</p><h3>6. Building Systems with Modules</h3><p>You can combine multiple tasks using a <strong>Module class</strong>.</p><p>Example: Blog → Summary + Title</p><pre>class BlogProcessor(dspy.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.summarizer = dspy.Predict(Summarize)<br>        self.title_gen = dspy.Predict(GenerateTitle)</pre><pre>    def forward(self, text):<br>        summary = self.summarizer(text=text).summary<br>        title = self.title_gen(summary=summary).title</pre><pre>        return {&quot;summary&quot;: summary, &quot;title&quot;: title}</pre><h3>7. The Real Problem: Output Quality</h3><p>Even with DSPy, outputs may not be great.</p><p>Traditionally, you would tweak prompts manually.</p><p><strong>Old Way</strong></p><pre>Try prompt → adjust → retry → repeat</pre><p><strong>DSPy Way</strong></p><pre>Define metric → provide examples → optimize automatically</pre><h3>8. DSPy Optimizer (Core Idea)</h3><p>DSPy Optimizers improve your program by:</p><ul><li>trying different prompts</li><li>testing outputs</li><li>selecting the best version</li></ul><p>Key Components</p><pre>Program + Training Data + Metric → Optimizer → Better Program</pre><h3>9. Training Data</h3><p>Training data is a set of examples:</p><pre>trainset = [<br>    {<br>        &quot;blog_post&quot;: &quot;DSPy simplifies AI development&quot;,<br>        &quot;tweet&quot;: &quot;Build AI apps faster with DSPy #AI&quot;<br>    }<br>]</pre><p>Important</p><ul><li>More diversity = better optimization</li><li>Quality matters more than quantity</li></ul><h3>10. Metric (Most Important Concept)</h3><p>Metric defines:</p><blockquote><em>“What is a good output?”</em></blockquote><p>Example</p><pre>def metric(example, prediction):<br>    return &quot;#&quot; in prediction.tweet and len(prediction.tweet) &lt; 280</pre><p>Why Metric Matters</p><p>If metric is wrong → optimization fails</p><p>Bad Metric</p><pre>len(tweet) &lt; 280</pre><p>Model ignores hashtags.</p><p>Better Metric</p><pre>def metric(example, prediction):<br>    return (<br>        len(prediction.tweet) &lt; 280 and<br>        &quot;#&quot; in prediction.tweet<br>    )</pre><p>Rule</p><pre>Bad output → Fix metric FIRST → Then data → Then model</pre><h3>11. MIPROv2 Optimizer (Advanced)</h3><p>BootstrapFewShot optimizes examples.</p><p>MIPROv2 goes further.</p><h4>What MIPROv2 does</h4><ul><li>improves instructions (docstring)</li><li>selects examples</li><li>optimizes structure</li></ul><p><strong>Code</strong></p><pre>from dspy.teleprompt import MIPROv2<br><br>optimizer = MIPROv2(metric=metric)<br>optimized_program = optimizer.compile(<br>    dspy.Predict(GenerateTweet),<br>    trainset=trainset<br>)</pre><h3>12. Complete Flow (End-to-End)</h3><pre>Step 1: Define Signature<br>Step 2: Choose Module (Predict / CoT)<br>Step 3: Create Training Data<br>Step 4: Define Metric<br>Step 5: Run Optimizer<br>Step 6: Use Optimized Program</pre><h3>13. Final Mental Model</h3><pre>Signature → WHAT<br>Module → HOW<br>Metric → QUALITY<br>Optimizer → IMPROVEMENT</pre><h3>14. When You Are Ready</h3><p>At this point, you can:</p><ul><li>build small DSPy apps</li><li>design clean pipelines</li><li>optimize outputs properly</li></ul><h3>Conclusion</h3><p>DSPy changes how you think about LLMs.</p><p>Instead of:</p><blockquote><em>“How do I write a better prompt?”</em></blockquote><p>You start thinking:</p><blockquote><em>“How do I define the task and measure quality?”</em></blockquote><h3>Final Thought</h3><blockquote><em>DSPy is not about prompting<br>It is about </em><strong><em>programming behavior using structure + evaluation</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7579c432e2fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Story of GPT: How AI Learned to Write, Code, and Think]]></title>
            <link>https://medium.com/@damodaran.selvaraj/the-story-of-gpt-how-ai-learned-to-write-code-and-think-3cb9dd24424f?source=rss-b50764aaf4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cb9dd24424f</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Damodaran Selvaraj]]></dc:creator>
            <pubDate>Sat, 23 May 2026 13:01:02 GMT</pubDate>
            <atom:updated>2026-05-23T13:01:02.684Z</atom:updated>
            <content:encoded><![CDATA[<h4>A beginner-friendly walkthrough of the evolution of GPT and the key papers that shaped modern language models.</h4><p>A few years ago, AI struggled to complete sentences. Today, it writes code, essays, and even passes professional exams. What changed? The answer lies in a series of models called GPT.</p><p><strong>GPT</strong> stands for <strong>Generative Pre-trained Transformer</strong>.</p><p>Break that down and you already have the whole story in three words:</p><p><strong>Generative</strong> — the model generates new text, one token at a time.</p><p><strong>Pre-trained</strong> — it first learns from enormous amounts of plain text before being asked to do anything specific.</p><p><strong>Transformer</strong> — the neural network architecture that powers it.</p><p>GPT models became important because they showed that a single, general-purpose language model — trained once on a lot of text — could be adapted to a huge range of tasks: translation, summarization, question answering, coding, conversation, and more. That idea reshaped how researchers and product teams build AI systems.</p><p>In this article, we’ll walk through the evolution of GPT models:</p><ul><li><strong>GPT-1</strong>(2018)</li><li><strong>GPT-2</strong> (2019)</li><li><strong>GPT-3</strong> (2020)</li><li><strong>GPT-3.5 </strong>(2022, building on InstructGPT)</li><li><strong>GPT-4</strong> (2023)</li><li><strong>GPT-5 </strong>(2025)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JbPAfLUZkZhXFpWvKP_78w.png" /><figcaption>AI generated Image</figcaption></figure><h3><strong>What is a Transformer?</strong></h3><p>Before GPT, most language models used <strong>RNNs (Recurrent Neural Networks)</strong> or <strong>LSTMs</strong>, which processed text sequentially. Transformers changed this completely.</p><p>A <strong>Transformer</strong> processes all words in a sentence <strong>at the same time</strong> using a mechanism called <strong>self-attention</strong>.</p><p>Think of it like this:</p><blockquote>Instead of reading a sentence word-by-word, the model looks at the entire sentence and decides which words are important for each other.</blockquote><p>I covered Transformer in more detail in my previous post. Click below.</p><p><a href="https://medium.com/@damodaran.selvaraj/transformer-in-ai-for-beginners-678014e3102b">Attention Is All You Need — But What Does That Actually Mean?</a></p><p>Key terms you need to know before we dive into GPT versions:</p><p><strong>Language model</strong> — a model that estimates the probability of the next token.</p><p><strong>Tokens</strong> — the small chunks (often sub-words) that text is split into before being fed to the model. The word “unhappiness” might become two or three tokens.</p><p><strong>Parameters</strong>— the numerical weights inside the neural network that are learned during training. More parameters generally means more capacity to store patterns.</p><p><strong>Pre-training — </strong>training the model on a large, general text dataset to learn general language patterns.</p><p><strong>Fine-tuning</strong> — taking that pre-trained model and continuing to train it on a smaller, labeled dataset for a specific task (like translation or QA).</p><p>GPT uses only the <strong>decoder</strong> half of the Transformer and is trained to predict the next token from left to right. That single, simple objective turns out to be remarkably powerful.</p><h3><strong>GPT-1(2018): The Beginning</strong></h3><p>Paper : <em>Improving Language Understanding by Generative Pre-Training</em></p><p>GPT-1’s core idea was that instead of training separate models for each language task, you could train one large model on unlabeled text, then fine-tune it for specific tasks with much smaller labeled datasets.</p><p>The process worked in two stages:</p><ol><li><strong>Unsupervised pre-training: </strong>The model learned from the BooksCorpus dataset (over 7,000 unpublished books) by simply predicting the next word in sentences. No human labeling required.</li><li><strong>Supervised Fine-Tuning (SFT): </strong>The pre-trained model was then adapted to specific tasks like sentiment analysis or question answering using smaller, task-specific datasets.</li></ol><h4>Model Architecture</h4><p>GPT‑1 uses the <strong>Transformer decoder only architecture.</strong></p><p>Important points:</p><ul><li><strong>12 decoder layers </strong>sequentially stacked</li><li><strong>12 attention heads </strong>in the multi‑head self‑attention mechanism in each decoder layer</li><li><strong>768 embedding </strong>dimension</li><li><strong>117 million trainable parameters</strong> (weights, Q, K, V matrices, biases, and embedding values)</li><li><strong>512 tokens Context window</strong> size</li></ul><p>The paper showed that this two-stage strategy achieved strong results across <strong>12 different NLP (Natural Language Processing) tasks</strong>, often outperforming models that had been trained specifically for each task.</p><h4>Limitations of GPT-1</h4><p>GPT-1 still had limitations:</p><ul><li>Smaller model size compared to recent systems</li><li>Weaker reasoning</li><li>Struggled with long and complex tasks</li></ul><p>Still, GPT-1 proved that scaling pre-training could work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mxtO0k4_4E-V63lSH1VjA.png" /><figcaption>AI generated Image</figcaption></figure><h3><strong>GPT-2 (2019): Bigger and More Capable</strong></h3><p><strong>Paper:</strong> <em>Language Models are Unsupervised Multitask Learners</em></p><blockquote>GPT-2 kept the same basic architecture but was much larger than GPT-1.</blockquote><h4>Model Architecture</h4><p>In the largest version of the model(1.5B model),</p><ul><li><strong>48 decoder layers </strong>sequentially stacked</li><li><strong>25 attention heads </strong>in the multi‑head self‑attention mechanism in each decoder layer</li><li><strong>1,600 embedding </strong>dimension</li><li><strong>1.5 billion trainable parameters</strong></li><li><strong>1,024 tokens Context window</strong> size</li></ul><h4><strong>Major Improvements:</strong></h4><p><strong>1. Dramatic Size Increase</strong><br>GPT-2&#39;s largest version contained <strong>1.5 billion parameters </strong>— roughly<strong> 10 times more than GPT-1</strong>. It was trained on<strong> WebText</strong>, a dataset of <strong>40GB of text from 8 million web pages</strong> (specifically, pages linked from Reddit posts with at least 3 upvotes).</p><p><strong>2. Impressive Text Generation</strong><br>GPT-2 could generate remarkably coherent, contextually appropriate text over multiple paragraphs. It could write convincing articles, stories, and even poetry. The quality was startling for its time.</p><p><strong>3. Zero-Shot Task Performance</strong><br>Perhaps most revolutionary, GPT-2 could perform tasks without any fine-tuning. You could give it a task through the prompt itself, and it would attempt to complete it based solely on its pre-training.</p><h4>Limitations :</h4><p>Despite its impressive capabilities, GPT-2 had clear weaknesses:</p><ul><li><strong>Hallucination: </strong>It would confidently generate false or nonsensical information</li><li><strong>Lack of understanding:</strong> It could produce fluent paragraphs about a topic without actually “knowing” anything as pattern matching, not reasoning.</li><li><strong>Inconsistency: </strong>Longer outputs often became incoherent or self-contradictory</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJaykVXAwbGGPPa_v1QwZQ.png" /><figcaption>AI generated Image</figcaption></figure><h3><strong>GPT-3 (2020): </strong>Prompting Becomes Programming</h3><p><strong>Paper:</strong> <em>Language Models are Few-Shot Learners</em></p><p>If GPT-2 was a bigger GPT-1, GPT-3 was a <em>much</em> bigger GPT-2 and that extra scale unlocked something qualitatively new.</p><p>From the paper:</p><blockquote><strong>“We train GPT-3, an autoregressive language model with 175 billion parameters.”</strong></blockquote><h4>Model Architecture</h4><p>In largest version of model,</p><ul><li><strong>96 decoder layers </strong>sequentially stacked</li><li><strong>96 attention heads </strong>in the multi‑head self‑attention mechanism in each decoder layer</li><li><strong>12,288 embedding </strong>dimension</li><li><strong>175 billion trainable parameters</strong></li><li><strong>2,048 tokens Context window</strong> size</li></ul><p>Training data was a mixture of filtered Common Crawl, WebText2, two book corpora (Books1 and Books2), and English Wikipedia.</p><h4>The Big Idea: In-Context Learning</h4><p>Instead of training the model again, you could <strong>teach it inside the prompt</strong>.</p><p>Here’s what that looks like in practice:</p><ul><li><strong>Zero-shot Prompt: </strong><em>“Translate the following English text to French: ‘The cat sat on the mat.’”</em> → GPT-3 generates the translation without ever seeing examples during training.</li><li><strong>One-shot: </strong>You provide one example of English→French, then ask it to translate a new sentence.</li><li><strong>Few-shot: </strong>You provide 3–5 examples, and the model grasps the pattern.</li></ul><h4>Limitations :</h4><p>GPT-3 was still imperfect as it hallucinated, struggled with arithmetic, and could be confidently wrong but it shifted how people <em>used</em> AI.</p><h3><strong>GPT-3.5 &amp; </strong>InstructGPT<strong>(2022): Better Conversations</strong></h3><p>Paper —<em> Training Language Models to Follow Instructions with Human Feedback</em></p><p>GPT-3.5 represents a series of improvements released throughout 2022. OpenAI hasn’t published a comprehensive research paper specifically about GPT-3.5, making exact technical details less publicly available.</p><p><strong>RLHF — Reinforcement Learning from Human Feedback:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sc7ShE_nNU2SqlMB6wBvg.png" /><figcaption>AI generated images</figcaption></figure><p>The 3-stage training process,</p><p>The paper’s training pipeline is the foundation for modern chat models.</p><h4>Step 1 — Supervised Fine-Tuning (SFT)</h4><p>Human contractors write high-quality demonstrations of how the model should answers for prompts. The model is then fine-tuned for these answers.</p><p>So instead of only learning:</p><blockquote>“What text usually comes next?”</blockquote><p>it starts learning:</p><blockquote>“What kind of answer do humans prefer?”</blockquote><h4>Step 2 — Reward Model Training</h4><p>Humans rank multiple model outputs for the same prompt</p><p>Example:</p><p>Prompt:</p><blockquote>“How do I learn Python?”</blockquote><p>Model generates 4 answers.</p><p>Humans rank them:</p><ol><li>Best</li><li>Good</li><li>Weak</li><li>Bad</li></ol><p>Then OpenAI trains another model called the <strong>Reward Model</strong>.</p><p>Its job:</p><ul><li>score outputs,</li><li>predict which answer humans would prefer.</li></ul><p>Think of it like a learned “human preference judge.”</p><h4>Step 3 — Reinforcement Learning (RLHF)</h4><p>This is the famous part. The language model now generates multiple answers for the same prompt. Now the Reward Model scores each answer. Then reinforcement learning adjusts the model to maximize human preference scores.</p><p>This is why it’s called:</p><blockquote><strong>Reinforcement Learning from Human Feedback (RLHF)</strong></blockquote><p>The optimization algorithm used was PPO:</p><blockquote><strong>PPO: Proximal Policy Optimization</strong></blockquote><p>Conceptually:</p><ul><li>good responses → rewarded,</li><li>bad responses → penalized,</li><li>model gradually becomes more aligned with human expectations.</li></ul><p>GPT-3.5 builds on this lineage and is the model family that powered the first version of ChatGPT in late 2022.</p><h3>GPT-4 (2023): The Leap Toward Reasoning</h3><p>Unlike earlier versions, OpenAI did something unusual: <em>They </em><strong><em>did not fully disclose</em></strong><em> the architecture, parameter count, or training data of gpt-4. </em>Instead of a traditional research paper, they released a <strong>technical report</strong> focused on:</p><ul><li>real-world performance</li><li>safety evaluations</li><li>benchmark results (including professional exams like the Bar Exam)</li></ul><p>GPT-4 is a multimodal large language model that processes both text and image inputs to generate text outputs. Context Window is <strong>128,000 tokens.</strong></p><p>Some reports suggest <strong>Mixture of Experts (MoE) </strong>architecture is used. OpenAI has not publicly confirmed GPT-4’s exact architecture or parameter count.</p><p><strong>Beyond GPT-4: Rapid Evolution:</strong></p><p>After GPT-4, progress accelerated quickly:</p><ul><li><strong>GPT-4 Turbo</strong> → faster, cheaper, longer context</li><li><strong>GPT-4o</strong> → real-time multimodal (text, image, audio)</li><li><strong>o-series models (o1, o3)</strong> → deeper reasoning focus</li><li><strong>Multimodal systems (like video generation)</strong> → expanding beyond text</li></ul><h3>GPT-5 (August 2025): OpenAI’s Unified AI System</h3><p>Unlike earlier generations where users manually selected different models, GPT-5 was designed as a <strong>unified system</strong> that intelligently decides when to respond quickly and when to spend more time reasoning through difficult problems.</p><p>GPT-5 significantly improved performance across:</p><ul><li>Coding</li><li>Mathematical reasoning</li><li>Writing</li><li>Scientific analysis</li><li>Visual understanding</li><li>Tool usage and agentic workflows</li></ul><h4>Safety and the GPT-5 System Card</h4><p>Alongside the release, OpenAI published a detailed GPT‑5 System Card explaining the model’s capabilities, limitations, and safety mitigations.</p><p>Some key safety improvements included:</p><ul><li>Reduced hallucinations</li><li>Better instruction following</li><li>Lower sycophancy (less tendency to blindly agree)</li><li>Stronger safeguards for harmful content</li></ul><h4>Why GPT-5 Matters</h4><p>GPT-5 represents a shift from “one giant model” toward an intelligent AI system that dynamically balances:</p><ul><li>Speed</li><li>Cost</li><li>Reasoning depth</li><li>Tool usage</li><li>Reliability</li></ul><h3>Final Thought:</h3><p>From GPT-1 to GPT-5, the progress is clear: better scale, better alignment, and better reasoning. What began as text prediction is now shaping how we write, code, and think. The technology is evolving fast — and those who understand it early will have the biggest advantage.</p><p><em>*Sources used for this article: the original OpenAI papers — “Improving Language Understanding by Generative Pre-Training” (2018), “Language Models are Unsupervised Multitask Learners” (2019), “Language Models are Few-Shot Learners” (2020), and “Training Language Models to Follow Instructions with Human Feedback” (2022).*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cb9dd24424f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BERT Explained: Google’s Breakthrough in AI Language Understanding]]></title>
            <link>https://medium.com/@damodaran.selvaraj/bert-explained-googles-breakthrough-in-ai-language-understanding-5ca56a0b64d2?source=rss-b50764aaf4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ca56a0b64d2</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[encoder]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Damodaran Selvaraj]]></dc:creator>
            <pubDate>Thu, 21 May 2026 13:31:00 GMT</pubDate>
            <atom:updated>2026-05-21T13:31:00.817Z</atom:updated>
            <content:encoded><![CDATA[<h4>BERT stands for Bidirectional Encoder Representations from Transformers.</h4><p>Google published this paper in 2018. It changed how machines understand human language forever.</p><h4>The World Before BERT: Pretty Good, But Limited</h4><p>The models before BERT had their own drawbacks.</p><p><strong>Word2Vec and GloVe</strong> gave us word embeddings in numerical representations that captured meaning. The word “king” would sit near “queen” in vector space, and you could do cool math like “king — man + woman ≈ queen.” These embeddings were <strong>context-independent</strong>. The word “bank” got the same vector whether you were talking about a river bank or a financial institution.</p><p><a href="https://medium.com/@damodaran.selvaraj/from-bag-of-words-to-word2vec-a-beginners-guide-to-word-embeddings-f87117509301">From Bag of Words to Word2Vec: A Beginner’s Guide to Word Embeddings</a></p><p><strong>LSTMs and RNNs</strong> tried to add context by reading sentences sequentially, word by word. Better! But they were slow, struggled with long-range dependencies, and could only read in one direction at a time — left to right. Imagine trying to understand a sentence while only allowed to read forward, never glancing back at what came before.</p><p><a href="https://medium.com/@damodaran.selvaraj/recurrent-neural-networks-rnns-explained-55f417f79163">Recurrent Neural Networks (RNNs) Explained</a></p><p>The fundamental issue? <strong>Traditional language models were unidirectional</strong>. They predicted the next word based only on previous words, which meant they couldn’t fully understand context that depends on words coming <em>after</em> the current position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Faaso8HXU6Hkbf8I19LwOQ.png" /><figcaption>AI generated image</figcaption></figure><h3>What Makes BERT Special?</h3><p><strong>Every word can see every other word in the sentence at once. </strong>This helps BERT understand the <strong>full context of a word. </strong>Instead of reading a sentence like reading left-to-right versus seeing the whole page at once, it reads the <em>entire sentence simultaneously</em> in both directions. This is why it’s called <strong>Bidirectional.</strong></p><p>Here is the core insight from the original paper by Devlin et al. at Google AI Language in 2018: <strong>pre-train deep bidirectional representations from unlabeled text by jointly conditioning on both left and right context in all layers.</strong></p><blockquote><strong>The Transformer made bidirectional context possible. BERT made it the core learning strategy.</strong></blockquote><blockquote><strong>While the Transformer encoder is inherently capable of bidirectional attention, BERT was the first model to fully exploit this capability through its training objective.</strong></blockquote><h3>How BERT Actually Works</h3><p>BERT is essentially a very deep, very well-read computer program built on the <strong>Transformer encoder</strong> architecture.</p><p>It uses <strong>attention mechanisms</strong> to:</p><ul><li>Focus on important words</li><li>Understand relationships between them</li></ul><p>In simple terms:</p><blockquote><strong>Every word looks at every other word before deciding its meaning.</strong></blockquote><p><a href="https://medium.com/@damodaran.selvaraj/transformer-in-ai-for-beginners-678014e3102b">Attention Is All You Need — But What Does That Actually Mean?</a></p><h3>How Was BERT Trained?</h3><p>BERT was trained using two clever tasks:</p><h4>1. Masked Language Model (MLM)</h4><p>BERT randomly hides 15% of the words in a sentence behind a [MASK] token. Then it tries to predict the hidden word based on everything else in the sentence. This forces the model to understand context from both sides.</p><blockquote><strong><em>“The cat sat on the mat and looked at the [MASK].”</em><br>BERT might guess “owner,” “bird,” or “camera.”</strong></blockquote><h4>2. Next Sentence Prediction (NSP)</h4><p>BERT also receives pairs of sentences and must answer a simple yes/no question: does sentence B logically follow sentence A?</p><p>Example:</p><blockquote><strong>Sentence A: “I love pizza”<br>Sentence B: “It is my favorite food” → Connected<br>Sentence B: “The moon is far away” → Not Connected</strong></blockquote><p>This task teaches BERT about <strong>relationships between sentences</strong>, which is crucial for question answering, natural language inference, and anything where context spans multiple paragraphs.</p><blockquote><strong>“BERT doesn’t predict the next word. It understands the missing one.”</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tV2mwFtqJPvlZmXWVGJXvQ.png" /><figcaption>Picture taken from Original BERT paper by Google</figcaption></figure><h3>Two Phases of BERT</h3><h4>Phase 1: Pre-Training (The Heavy Lifting)</h4><p>This is the expensive part. Google trained BERT on 3.3 billion words (English Wikipedia + the BooksCorpus of unpublished fiction). For days, BERT played MLM and NSP on powerful TPUs. This stage requires serious compute, but the output is a general-purpose language genius.</p><h4>Phase 2: Fine-Tuning (The Quick Specialization)</h4><p>Take the pretrained BERT, swap out the final layer for a tiny task-specific head, and train on your labeled data for just 2–4 epochs.</p><p>Want sentiment analysis? Add a classification layer on top of the [CLS] token and feed it movie reviews.</p><p>Want question answering? Add a span-prediction head and feed it SQuAD examples.</p><p>Want named entity recognition? Add a token-level classifier and feed it tagged sentences.</p><p>The architecture barely changes. BERT already <em>knows</em> English. You are just teaching it the format of your specific exam.</p><h3>Two Sizes, One Architecture</h3><p>The original BERT paper (Devlin et al., 2018) introduced two model sizes:</p><ul><li><strong>BERT-Base</strong>: 12 Transformer encoder layers, 110 million parameters</li><li><strong>BERT-Large</strong>: 24 layers, 340 million parameters</li></ul><p>Both use the same fundamental approach, just at different scales. BERT-Large generally performs better but requires more computational power.</p><h3>Getting Text Into BERT: The Input Recipe</h3><p><strong>Step 1: Tokenization</strong><br>BERT uses <strong>WordPiece tokenization</strong>, which breaks words into subword units. “playing” might become [“play”, “##ing”]. This handles rare words elegantly — even if BERT has never seen “unbelievability,” it knows “un,” “believab,” “##ility.”</p><p><strong>Step 2: Special Tokens</strong><br> Every input gets wrapped with special markers:</p><ul><li>[CLS] at the start (used for classification tasks)</li><li>[SEP] to separate sentences when processing pairs</li></ul><p>So “I love coffee. Coffee is life.” becomes:<br> [CLS] I love coffee [SEP] Coffee is life [SEP]</p><p><strong>Step 3: Three Embeddings Combined</strong><br> Each token gets three pieces of information added together:</p><ol><li><strong>Token embedding</strong>: What word is this? (like a name tag)</li><li><strong>Segment embedding</strong>: Which sentence does it belong to? (like a room number)</li><li><strong>Position embedding</strong>: Where in the sequence is it? (like a seat number)</li></ol><p>Think of it as giving every word a complete address: “I’m the word ‘coffee’ (token), in sentence A (segment), at position 3 (position).”</p><h3>Why BERT Still Matters Today</h3><p>BERT didn’t just win benchmarks. It shifted the entire philosophy of NLP.</p><p>Before BERT, most teams trained models from scratch on small labeled datasets and prayed they generalized. After BERT, the default became: <strong>download a pretrained giant, fine-tune it on your niche data, and deploy.</strong></p><p>This democratized high-performance NLP. A startup with one GPU and 1,000 labeled examples could now compete with teams that previously needed millions of labels and months of training.</p><p>It also kicked off a family of descendants:</p><ul><li><strong>RoBERTa</strong> (Facebook) — trained longer, dropped NSP, stronger results.</li><li><strong>DistilBERT</strong> — a smaller, faster BERT that retains 97% of performance.</li><li><strong>ALBERT</strong> — shared parameters and factorized embeddings, far lighter.</li></ul><p>Some researchers even coined the term <strong>“BERTology”</strong> to study what these models learn internally. BERT became a platform, not just a paper.</p><h3>BERT Limitations</h3><ul><li><strong>Computational cost</strong> — expensive pretraining and slower inference</li><li><strong>Fixed sequence length</strong> — the 512 token limit and chunking challenges</li><li><strong>Not great at generation</strong> — encoder vs. decoder architecture trade-offs</li><li><strong>The </strong><strong>[MASK] mismatch</strong> - pretrain/fine-tune discrepancy</li><li><strong>NSP skepticism</strong> — later research questioning its value</li></ul><h3>Final Thought</h3><p>BERT taught us that sometimes the best way to understand language isn’t to predict what comes next, but to see everything at once and fill in the gaps. It’s bidirectional. It’s powerful. And six years later, it’s still influencing every major language model we build.</p><blockquote>If BERT is about understanding language, the next evolution of GPT 2/3 is about generating it.</blockquote><p><strong>Reference:</strong><br>Devlin, J., Chang, M.-W., Lee, K., &amp; Toutanova, K. (2018). <em>BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.</em> Google AI Language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ca56a0b64d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attention Is All You Need — But What Does That Actually Mean?]]></title>
            <link>https://medium.com/@damodaran.selvaraj/transformer-in-ai-for-beginners-678014e3102b?source=rss-b50764aaf4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/678014e3102b</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-for-beginners]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Damodaran Selvaraj]]></dc:creator>
            <pubDate>Sat, 02 May 2026 16:22:04 GMT</pubDate>
            <atom:updated>2026-05-02T16:24:21.372Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step beginner guide to attention, encoders, and decoders — with clear intuition and simple examples</h4><p>Have you ever wondered how ChatGPT reads your entire question and gives a perfect answer in seconds?</p><p>It does <strong>not read word by word</strong> like an old typewriter.</p><p>It reads everything at once and figures out which words matter most. That secret power comes from something called a <strong>Transformer.</strong></p><p>In 2017, a team at Google published a paper with a bold title:</p><blockquote><strong>“Attention Is All You Need”</strong></blockquote><p>That paper introduced the Transformer. It changed everything.</p><p>Every modern AI tool you use today ChatGPT, Google Translate, Gemini runs on this idea.</p><p><strong>In this beginner-friendly guide, you will learn:</strong></p><ul><li>What a Transformer?</li><li>What <strong>“Attention is All You Need”</strong> really means?</li><li>Why old AI models failed and how Transformers fixed them?</li><li>How the attention mechanism works?</li><li>The difference between Encoders and Decoders</li></ul><h3>What is Transformer in AI?</h3><p>A <strong>Transformer</strong> is a type of deep learning model used in <strong>AI .</strong></p><p><strong>Artificial Intelligence (AI)</strong> means machines that can learn and make decisions.</p><p>Transformers help machines understand and generate human language.</p><p>A <strong>Transformer</strong> is a model that reads text and understands relationships between words using something called <strong><em>attention</em>.</strong></p><p>Before Transformers, models read text one word at a time.<br>That was slow and inefficient.</p><p>Transformers changed this by:</p><ul><li>Reading all words <strong>at once</strong></li><li>Understanding <strong>context better</strong></li><li>Running faster on modern hardware</li></ul><h3>Where Are Transformers Used in Real Life?</h3><ul><li>ChatGPT — Answers your questions using a Transformer</li><li>Google Translate — Translates languages using a Transformer</li><li>Spotify — Recommends songs using Transformer-based models</li><li>Gmail Smart Reply — Suggests email replies using Transformers</li><li>DALL-E — Generates images using a Transformer variant</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*yGhsCO6e3yIpN4gG59ek-Q.png" /><figcaption>Model Architecture diagram from orginal paper “Attention Is All You Need”</figcaption></figure><h3>How Does a Transformer Work? (Step-by-Step)</h3><p>A Transformer has two main parts:</p><ol><li><strong>Encoder</strong> — The Reader</li><li><strong>Decoder</strong> — The Writer</li></ol><h4>The Encoder — “The Reader”</h4><p>The Encoder reads the input text.<br>It processes and understands the meaning of the sentence.<br>It converts words into rich, meaningful numbers that capture context.</p><h4>The Decoder — “The Writer”</h4><p>The Decoder takes those notes and generates an output.<br>For translation → writes sentence in another language<br>For ChatGPT → predicts next word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*Vagud-D_25e6DslF-FsCaA.png" /><figcaption>AI generated Image</figcaption></figure><h3>Steps Inside a Transformer</h3><h4>Tokenisation — Turning Words into Numbers</h4><p>The text gets split into small pieces called <strong>tokens</strong> (often a word, part of a word, or punctuation).</p><pre>&quot;Hello world&quot; → [&quot;Hello&quot;, &quot;world&quot;]</pre><h4>Embedding — Giving Tokens Meaning</h4><p>Each token ID is converted into a <strong>dense vector</strong> — a list of numbers that captures the word’s meaning.</p><pre>&quot;Hello&quot; → [0.21, -0.45, 0.87, ...]</pre><p>Refer my previous post to understand NLP and Word embedding.</p><ul><li><a href="https://medium.com/@damodaran.selvaraj/nlp-for-beginners-how-machines-understand-text-step-by-step-guide-aa858d559458">NLP for Beginners: How Machines Understand Text (Step-by-Step Guide)</a></li><li><a href="https://medium.com/@damodaran.selvaraj/from-bag-of-words-to-word2vec-a-beginners-guide-to-word-embeddings-f87117509301">From Bag of Words to Word2Vec: A Beginner’s Guide to Word Embeddings</a></li></ul><h4>Positional Encoding — Telling the Model Where Words Are</h4><p>Transformers don’t read sequentially, so they don’t automatically know word order.</p><p>We must explicitly inject information about each token’s <strong>position</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*xUfvQFDiNc98VGqHDs4wtw.png" /><figcaption>Positional Encoding formula from “Attention Is All You Need” paper</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUaZdjM-NRt1UsFp5lZRXg.png" /><figcaption>AI generate image</figcaption></figure><h3>Encoder Layer Structure</h3><ul><li>Multi-Head Attention</li><li>Add &amp; Norm</li><li>Feed Forward Network</li><li>Add &amp; Norm again</li></ul><p>“Add &amp; Norm” = Residual Connection + Layer NormalizationEach encoder layer has this structure:</p><h3>What is Attention in Transformers?</h3><p>When you read a sentence, you don’t treat every word equally. You <strong>focus </strong>on important words.</p><blockquote>That is exactly what <strong>attention</strong> does in a Transformer.</blockquote><p><strong>Attention</strong> is a mechanism that helps a model focus on the most important words in a sentence.</p><h4>How It Works (Step-by-Step):</h4><p>For each token, we create three vectors:</p><ul><li><strong>Query (Q):</strong> “What am I looking for?”</li><li><strong>Key (K):</strong> “What do I offer?”</li><li><strong>Value (V):</strong> “What is my actual content?”</li></ul><p>These are just numbers describing how long each vector is. A vector is simply a list of numbers representing meaning.</p><pre>Q = [0.21, 0.85, -0.43, ...]  ← list of d_k numbers<br>K = [0.67, -0.12, 0.91, ...]  ← list of d_k numbers<br>V = [0.34, 0.55, -0.78, ...]  ← list of d_v numbers</pre><p>We compare the <strong>Query</strong> of word A with the <strong>Keys</strong> of all words (including itself) to compute attention scores. These scores tell us how much of each word’s <strong>Value</strong> to mix into the new representation of word A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEyPkQ_knCLdqObGxodUOQ.png" /><figcaption>AI generate image</figcaption></figure><p><strong>Scaled Dot-Product Attention formula:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAHjjQz3ZP82HkZ5uOmLvw.png" /><figcaption>Formula from “Attention Is All You Need” paper</figcaption></figure><p><strong>Step 1: Compute the Dot Product — QKᵀ</strong></p><p>Multiply Q and K together. This gives a score for every pair of words. A high score means “these two words are strongly related.”</p><p><strong>Step 2: Scale by √dₖ (The “Scaled” Part)</strong></p><p>Divide every score by √dₖ. Without scaling, the scores become huge numbers. Huge numbers make the next step (softmax) behave badly. It becomes too confident too fast and stops learning properly. Dividing by √dₖ keeps the scores in a healthy, <strong>stable range.</strong></p><p><strong>Step 3: Apply Softmax</strong></p><p>Softmax is a function that converts a list of raw scores into probabilities that add up to 1.</p><pre>Before softmax:<br>Scores: [3.2, 0.1, 1.4, 0.3]<br>After softmax:<br>Probabilities: [0.72, 0.04, 0.19, 0.05]<br>                ↑ This word gets 72% of the attention</pre><p>The word with the highest score gets the most attention. The others get less. This is literally how the model <strong>“pays attention.”</strong></p><p><strong>Step 4: Multiply by V (Values)</strong></p><p>Finally, multiply the probabilities by the Value vectors. This gives you a <strong>weighted combination</strong> of all word meanings — where important words contribute more.</p><p>The output is a new, rich representation of each word. Now enriched with <strong>context from the whole sentence.</strong></p><h4>Why Attention is Powerful</h4><ol><li><strong>Looks at Full Sentence</strong> — Unlike old models, attention sees all words at once.</li><li><strong>Captures Long Relationships</strong> — It connects words far apart.</li><li><strong>Dynamic Focus</strong> — It changes focus depending on context.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4U8YBuJ__ltPYIirGdMJw.png" /><figcaption>Diagram from orginal paper “Attention Is All You Need”</figcaption></figure><h3>What is Multi-Head Attention?</h3><p><strong>Multi-Head Attention</strong> is a core part of the Transformer.</p><p>Instead of doing attention once, we do it <strong>multiple times in parallel</strong>. Each version is called a <strong>head</strong>.</p><h4>Why “multiple heads”?</h4><p>One attention layer may miss some relationships. So we use multiple heads to learn different patterns.</p><p>Think of it like this:</p><ul><li>One head focuses on <strong>grammar</strong></li><li>Another focuses on <strong>meaning</strong></li><li>Another focuses on <strong>relationships</strong></li></ul><p>Each head looks at the same sentence in a <strong>different way</strong>.</p><blockquote><strong><em>Single attention</em></strong><em> = one perspective<br></em><strong><em>Multi-Head Attention</em></strong><em> = many perspectives simultaneously</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wxx5WR1Tr_uZ6LoQvqZV5w.png" /><figcaption>AI generated Image</figcaption></figure><h4>The Multi-Head Attention Formula</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*B7PmNNWQAvxT_gWeD5A3DA.png" /><figcaption>Formula from “Attention Is All You Need” paper</figcaption></figure><ul><li>h — Number of heads</li><li>W_i^Q — Query projection matrix for head i</li><li>W_i^K — Key projection matrix for head i</li><li>W_i^V — Value projection matrix for head i</li><li>W^O — Output projection matrix</li><li>Concat — Concatenation​</li></ul><h4>The Dimensions</h4><pre>d_model = 512  → The full model dimension (size of every vector in the model)<br>h = 8          → 8 attention heads running in parallel<br>d_k = d_v = 512 / 8 = 64  → Each head works with smaller 64-dim vectors</pre><blockquote><strong>Why split dimensions?</strong> If the full model uses 512 dimensions and you have 8 heads, each head gets 64 dimensions. The total work stays the same — but you get <strong>8 different perspectives</strong> instead of one.</blockquote><blockquote>It has similar computational cost but provides richer representations.<em> You get 8x the perspectives for the same computational cost.</em></blockquote><h3>What is a Residual Connection?</h3><p>A <strong>Residual Connection</strong> (also called a skip connection) takes the input to a layer and adds it directly to the output.</p><pre>x → Multi-Head Attention → attention_output<br>output = attention_output + x</pre><p>So we keep both:</p><ul><li><strong>New information</strong> (from attention)</li><li><strong>Original input</strong> (preserved via the skip)</li></ul><h4>Why This is Brilliant</h4><p>The model stacks <strong>N = 6 Encoder layers</strong> are <strong>stacked sequentially,</strong> meaning the output of one encoder layer serves as the input to the next. Without residual connections, training 6 stacked layers is extremely difficult for gradients vanish and the model stops learning.</p><p>With residual connections, gradients flow directly through the skip path — bypassing the complex sub-layer. Training becomes <strong>stable</strong> even with many layers.</p><h3>What is Layer Normalization?</h3><p><strong>Normalization</strong> means scaling values to a stable range. <strong>Layer Normalization (LayerNorm)</strong> normalizes the values across the features of each individual token, ensuring consistent scale throughout training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*616O8BAY2J6O5oBwrYE64A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*X4uqC3gcO014trzkxTWcfA.png" /></figure><h3>What is the Position-wise Feed-Forward Network?</h3><p>After Attention and the first Add &amp; Norm, the data enters the second sub-layer — the <strong>Feed-Forward Network (FFN)</strong>.</p><p>The FFN processes each token <strong>independently</strong> and adds depth to the model’s understanding.</p><blockquote><strong>Attention</strong> is a group discussion — everyone talks to each other.<br><strong>The FFN</strong> is personal study time — each person processes what they learned, alone.</blockquote><p>The FFN gives each token a chance to “think deeply” about its own representation after seeing all the context from Attention.</p><blockquote>While Attention handles relationships <strong>between</strong> tokens, the FFN refines <strong>each token’s own</strong> representation.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHebg-HG1tGUbdELziVYkQ.png" /></figure><p>So the FFN works like this:</p><pre>Input:          512 dimensions<br>     ↓ W_1 (512 → 2048)<br>Expanded:      2048 dimensions  ← Inner layer (d_ff)<br>     ↓ ReLU<br>Still:         2048 dimensions<br>     ↓ W_2 (2048 → 512)<br>Output:         512 dimensions  ← Back to d_model</pre><p>The network expands by a factor of 4 (512 → 2048), then compresses back (2048 → 512).</p><p><strong>What does the FFN do that Attention does not?</strong></p><p><strong>Multi-Head Attention — </strong>Learns <em>relationships between</em> tokens (how words relate to each other across the sentence)</p><p><strong>Feed-Forward Network — </strong>Learns <em>properties of individual</em> tokens (processes each token’s meaning more deeply, in isolation)</p><p><strong>Is the FFN the same for all 6 Encoder layers?</strong></p><p><strong>No.</strong> Each of the 6 Encoder layers has its <strong>own independent FFN</strong> with its own learned weights. The layers are<strong> “identical in structure” but not in weights.</strong> Earlier layers learn basic patterns; later layers learn complex ones.</p><blockquote><strong>Transformer Flow:</strong></blockquote><blockquote>Text → Tokens → Embeddings → Attention → Encoder → Decoder → Softmax → Word</blockquote><h3>Structure of the Decoder</h3><p>Each decoder layer has <strong>three</strong> sub-layers (vs. two in the Encoder):</p><pre>Masked Multi-Head Attention<br>         ↓<br>      Add &amp; Norm<br>         ↓<br>Cross Multi-Head Attention<br>         ↓<br>      Add &amp; Norm<br>         ↓<br>  Feed Forward Network<br>         ↓<br>      Add &amp; Norm</pre><p><strong>How Is the Decoder Different?</strong></p><ul><li>The <strong>Encoder</strong> runs <strong>once</strong> on the full input.</li><li>The <strong>Decoder</strong> runs <strong>multiple times</strong> — once for each output token it generates.</li></ul><p><strong>One Decoder Layer has three Sub-Layers</strong></p><p>Three sub-layers are:</p><ol><li><strong>Masked </strong>Multi-Head Self-Attention (new — unique to Decoder)</li><li>Multi-Head <strong>Cross</strong>-Attention (new — connects Encoder and Decoder)</li><li>Position-wise Feed-Forward Network (same as Encoder)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*3KMfp7Fe3JLh8ceM0tqmsw.png" /><figcaption>AI generate Image</figcaption></figure><h3>Sub-Layer 1 — Masked Multi-Head Self-Attention</h3><h4>How Does the Decoder Generate Text? (Autoregressive Decoding)</h4><p><strong>Autoregressive</strong> means: the output of the previous step becomes the input of the next step. Each step, the Decoder sees everything it has generated so far and uses that context plus the Encoder’s output to predict the next word.</p><h4>What is Masking? (The Core Idea)</h4><ul><li>When generating word at position i, the model can ONLY look at positions 1 to i-1</li><li>It cannot look at positions i+1, i+2, … (the future)</li><li>Future positions are masked — blocked from view</li></ul><p>The mask is applied BEFORE the softmax. Future positions get their scores set to negative infinity (−∞).</p><h4>Why Is It Still “Multi-Head”?</h4><p>Everything else about Multi-Head Attention remains identical. We still have:</p><ul><li>h = 8 parallel attention heads</li><li>Projections W^Q, W^K, W^V, W^O</li><li>Scaled Dot-Product Attention in each head</li><li>Concatenation and output projection</li></ul><p>The ONLY difference from Encoder self-attention is the <strong>mask applied before softmax.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*XqobNVNiTzEHO6jp_46vtw.png" /><figcaption>AI generated Image</figcaption></figure><h3>Sub-Layer 2 — Multi-Head Cross-Attention (Encoder-Decoder Attention)</h3><p>This is the most <strong>unique and important</strong> part of the Decoder — the bridge between Encoder and Decoder.</p><h4>What is Cross-Attention?</h4><p>In the Encoder, self-attention means Q, K, and V all come from the <strong>same</strong> source. But Cross-Attention is different.</p><pre>Q = output of the previous Decoder sub-layer (after Masked Self-Attention + Add &amp; Norm).<br>K = encoder output<br>V = encoder output</pre><h4>The Cross-Attention Flow</h4><pre>Encoder Output (memory)<br>    ├─── K (Keys)   ──────────────────────────┐<br>    └─── V (Values) ──────────────────────────┤<br>                                              ▼<br>Decoder (after masked attention)         Cross-Attention<br>    └─── Q (Queries) ─────────────────────────┘<br>                                              │<br>                                              ▼<br>                                  Output: context-enriched<br>                                  Decoder representations</pre><h4>Why Doesn’t Cross-Attention Need a Mask?</h4><p>Because the Encoder output is <strong>already complete</strong>. The entire input sentence has been processed. There are no “future” Encoder positions to hide. The Decoder can freely attend to <strong>all</strong> Encoder positions. This is intentional and important, sometimes the last word of a sentence is crucial for understanding the first word of the translation.</p><h3>Sub-Layer 3 — Position-wise Feed-Forward Network</h3><p>Same as the Encoder’s FFN — each token refines its own representation after seeing context from both the Masked Self-Attention and Cross-Attention layers.</p><h3>What Happens After the Decoder?</h3><p>Let’s see the flow.</p><pre>Decoder Output → Linear Layer → Softmax → Final Prediction</pre><h4>Step 1: Decoder Output</h4><p>After the <strong>decoder</strong> finishes its work, it produces a list of numbers. These numbers are called <strong>logits</strong>. It is raw scores for each possible word in the vocabulary.</p><pre>[0.3, -1.2, 2.5, ...]</pre><p>This vector represents hidden meaning.</p><h4>Step 2: Linear Layer</h4><p>A linear layer is just a matrix multiplication that reshapes one set of numbers into another.</p><p>A linear layer converts hidden values into vocabulary scores. <br>If your <strong>vocabulary has 10,000 words</strong>, you get <strong>10,000 logits.</strong></p><h4>Step 3: Apply Softmax</h4><p>Softmax converts logits into <strong>probabilities</strong> — values between 0 and 1 that add up to 1.</p><pre>Logits:        [0.3, -1.2, 2.5, ...]<br>Probabilities: [0.08, 0.01, 0.74, ...]</pre><p><strong>Why Do We Need Softmax?</strong></p><p>We want the model to answer:</p><blockquote>“What is the most likely next word?”</blockquote><p>To do that, we must convert logits into probabilities. This is where <strong>softmax</strong> comes in.</p><h4>Step 4: Choose the Next Word</h4><p>Pick either:</p><ul><li><strong>Highest probability</strong> → greedy decoding (predictable)</li><li><strong>Sample from probabilities</strong> → creative output (varied)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kY45ZLyOaFIWSurGqwHXhg.png" /><figcaption>AI generated image</figcaption></figure><h3>Critical Concepts Recap</h3><p><strong>1. Tokenisation </strong>comes before everything. Without it, the model has no input.<br><strong>2. Positional Encoding </strong>is non-negotiable. Transformers are order-blind without it — removing it means the model treats “Dog bites man” and “Man bites dog” identically.<br><strong>3. The √dₖ scaling </strong>in attention is subtle but critical. Skip it and your model’s softmax explodes, gradients vanish, and training breaks.<br><strong>4. Residual Connections </strong>are what make deep stacking (6 layers) trainable at all. Without them, gradients die.<br><strong>5. Masking in the Decoder</strong> is what prevents “cheating” during training. Without it, the model learns a shortcut that doesn’t work at inference time.<br><strong>6. Cross-Attention </strong>is what ties the Encoder and Decoder together. Without it, the Decoder has no way to reference the original input — translation becomes impossible.</p><blockquote>The genius of the Transformer is that <strong>every piece is simple on its own</strong>. Tokens become vectors. Vectors get scored against each other. Scores become probabilities. Probabilities select the next word. Repeat.</blockquote><blockquote><strong>That’s the Transformer. That’s “Attention Is All You Need.”</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=678014e3102b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Bag of Words to Word2Vec: A Beginner’s Guide to Word Embeddings]]></title>
            <link>https://medium.com/@damodaran.selvaraj/from-bag-of-words-to-word2vec-a-beginners-guide-to-word-embeddings-f87117509301?source=rss-b50764aaf4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f87117509301</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[bert]]></category>
            <dc:creator><![CDATA[Damodaran Selvaraj]]></dc:creator>
            <pubDate>Sat, 02 May 2026 05:38:03 GMT</pubDate>
            <atom:updated>2026-05-02T05:38:03.053Z</atom:updated>
            <content:encoded><![CDATA[<h4>From counting words to understanding meaning — a beginner-friendly journey through Word Embeddings.</h4><p>How does a machine understand that:</p><blockquote>“king” is similar to “queen” but completely different from “apple”?</blockquote><p>Words are just text for us, but machines need <strong>numbers</strong>. That transformation is called <strong>Word Embedding</strong>.</p><p>In Natural Language Processing (NLP) text data needs to be converted into numbers so that machine learning algorithms can understand it.</p><h3>What Is A Corpus?</h3><p>Before anything starts, machines need data.</p><p>A <strong>corpus</strong> is simply a collection of text data used in NLP.</p><p>Think of it like this:</p><ul><li>Students learn from textbooks</li><li>Machines learn from corpora</li></ul><blockquote><strong>Corpora = Large collections of text used to train NLP systems</strong></blockquote><h3>What Are Word Embeddings?</h3><p>Word embeddings are a <strong>real-value vector representation of a word</strong>.</p><p>Example :</p><ul><li>king → [0.21, -0.83, 0.44, …]</li><li>queen → [0.19, -0.79, 0.41, …]</li><li>apple → [-0.67, 0.31, -0.12, …]</li></ul><p>Each word becomes a list of numbers.</p><blockquote><strong>In practice, Vectors usually have 100–300 dimensions (traditional models) or 768+ in modern models like BERT, GPT. Each number alone means nothing but together they encode meaning.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0pg-WLMjVmoF_0VzPRpBA.png" /><figcaption>AI generated image</figcaption></figure><h3>The Evolution Of Word Embeddings</h3><h3>1. Frequency Based Embedding</h3><h4>A) Bag of Words (BoW)</h4><p>Imagine taking a sentence:</p><blockquote>“a chapter is part of a book”</blockquote><p>Now throw all words into a bag:</p><ul><li>No grammar</li><li>No order</li><li>Just counts</li></ul><p>That’s <strong>Bag Of Words</strong>.</p><p>It converts text into a <strong>word frequency matrix.</strong></p><blockquote>If your vocabulary has 10,000 words, every single word becomes a list of 10,000 numbers (mostly zeros).</blockquote><p><strong>Key Idea:</strong></p><ul><li>Focuses only on <em>how many times a word appears</em></li><li>Ignores meaning and structure</li></ul><p><strong>Problem With Bag Of Words</strong></p><ul><li>“dog bites man” = “man bites dog”</li><li>No understanding of meaning</li></ul><h4>Binary Bag Of Words (BBoW)</h4><p>It is a variation of the traditional Bag of Words (BoW) model. While the BoW model counts the frequency of each word occurrence in a document, the Binary Bag of Words model simply indicates whether a word is present or absent in the document i.e. <strong>we just mark 1 or 0 </strong>if a particular word is present or not respectively, disregarding its frequency.</p><p>BoW creates <strong>Sparse Matrices,</strong> huge tables of zeros that waste computer memory. <strong>Word2Vec creates Dense Vectors</strong>, which are small, packed with information, and much faster to process.</p><p><strong>Note:</strong> Matrices that contain mostly zero values are called <strong>sparse matrix,</strong> distinct from matrices where most of the values are non-zero, called <strong>dense matrix.</strong></p><h4>B) N-Grams (Adding Context)</h4><p>To fix this, we use <strong>N-grams.</strong> N-gram models consider a sequence of ’n’ words. This captures more context. However, it still misses out on the semantics of words.</p><p>Example Sentence:</p><blockquote>“a chapter is part of a book”</blockquote><ul><li>Unigram (n=1, single words) → “a” “chapter”, “is”, “part”</li><li>Bigram (n=2, pairs) → “a chapter”, “chapter is”, “is part”</li><li>Trigram (n=3, triplets) → “a chapter is ”, “chapter is part”</li></ul><p>This captures <em>some context</em> , but still no real meaning. It uses a <strong>sliding window of words as context.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tfj7tgw0xh0iedK-JR_cIQ.png" /><figcaption>AI generated Image</figcaption></figure><h4>C) TF-IDF (Smarter Counting)</h4><p><strong>Term Frequency (TF):</strong> Term frequency measures <strong>how frequently a term appears in a document.</strong> It is calculated as the ratio of the number of times a term occurs in a document to the total number of terms in the document.</p><p><strong>Inverse Document Frequency (IDF): </strong>Inverse document frequency measures <strong>how unique or rare a term is across a collection of documents.</strong> It is calculated as the logarithm of the ratio of the total number of documents in the corpus to the number of documents containing the term.</p><p>The TF-IDF approach weighs words based on their importance. It’s calculated across a set of documents. This reflects how relevant a word is for a particular document.</p><blockquote><strong>TF = (How often the word appears in this document) / (Total words in this document)</strong></blockquote><blockquote><strong>IDF = log(Total documents / Documents containing the word)</strong></blockquote><blockquote><strong>TF-IDF = TF × IDF</strong></blockquote><blockquote><strong>Words that appear often in one document but rarely in others get high scores. Common words like “the” get penalized.</strong></blockquote><h3>2. Prediction Based Embedding (The Breakthrough)</h3><h4>A) Word2Vec — The Game Changer</h4><p>Word2Vec, short for <strong>“word to vector,”</strong> was developed at <strong>Google in 2013 </strong>by Tomas Mikolov. It is a <strong>prediction-based model</strong> that uses a <strong>shallow two-layer </strong>neural network (an input and two layer — one hidden layer, and an output layer).</p><p>It represents each distinct word with a particular list of numbers called a <strong>vector.</strong> Instead of counting words. It <strong>learns meaning by prediction.</strong></p><p>It processes a corpus by sliding a window over the text to:</p><ul><li>Predict a word based on its neighbors — <strong>Continuous Bag of Words (CBOW)</strong></li><li>Predict neighbors based on a target word <strong>(Skip-Gram)</strong></li></ul><p>It learns by iterating through the text and adjusting vectors locally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1IMWDVb3bUyHmwaaCWw95g.png" /><figcaption>AI generated Image</figcaption></figure><h4>1. CBOW (Continuous Bag of Words)</h4><p>The CBOW model predicts the current word given context words within a specific window. The input layer contains the context words and the output layer contains the current word. The hidden layer contains the dimensions we want to represent the current word present at the output layer.</p><h4>2. Skip Gram</h4><p>The<strong> </strong>Skip gram predicts the surrounding context words within specific window given current word. The input layer contains the current word and the output layer contains the context words. The hidden layer contains the number of dimensions in which we want to represent current word present at the input layer.</p><pre>vector(&quot;king&quot;) - vector(&quot;man&quot;) + vector(&quot;woman&quot;) ≈ vector(&quot;queen&quot;)</pre><p><strong>Limitations Of Word2Vec</strong></p><ol><li>Fixed Vocabulary (cannot handle new words)</li><li>Domain Dependency</li><li>Static Embeddings</li></ol><p><strong>Example: “bank” (river vs money) → same vector</strong></p><h4>B) GloVe (Global Vectors)</h4><p>GloVe <strong>(Global Vectors for Word Representation)</strong> is an unsupervised learning algorithm that creates dense word embeddings by analyzing the global co-occurrence patterns of words across a large text corpus. By building a word-word co-occurrence matrix, it captures both semantic and syntactic relationships between words, allowing models to understand nuances in meaning based on how frequently words appear together.</p><ul><li><strong>Global Statistics:</strong> Unlike models that focus only on local context (like Word2Vec’s sliding window), GloVe aggregates statistics from the entire corpus, giving it a broader perspective on word relationships.</li><li><strong>Co-Occurrence Matrix: </strong>The algorithm starts by tabulating how often each word appears with every other word in a given text.</li></ul><h4>C) FastText (Fixing Word2Vec’s Weakness)</h4><p><strong>FastText</strong> is an extension of Word2Vec developed by <strong>Facebook’s AI Research</strong> (FAIR) lab that addresses the major limitation of Word2Vec: the inability to handle <strong>out-of-vocabulary (OOV) words and rare words.</strong> While Word2Vec treats each word as an atomic unit, FastText breaks words down into subword units (character n-grams), allowing it to understand the internal structure of words and generate representations for unseen terms.</p><h3>3. Contextualized Word Embeddings (Modern NLP)</h3><p>The Problem With Older Models</p><p>Word2Vec, GloVe, FastText: <strong>One word = one vector</strong></p><p>But “bank” (river) ≠ “bank” (money). Still same vector</p><h4>Modern Models Solve This</h4><ul><li>BERT → encoder-based, bidirectional, great for understanding tasks</li><li>GPT → decoder-based, autoregressive, great for generation</li></ul><p>Key idea: <strong>same word → different vectors based on context</strong></p><h3>Semantic vs Syntactic Understanding</h3><p>Language has two parts:</p><ul><li>Syntax → structure</li><li>Semantics → meaning</li></ul><p>Word embeddings aim to capture both.</p><h3>Final Summary</h3><h4>Evolution:</h4><ol><li>Bag Of Words → Counting words</li><li>TF-IDF → Scoring words</li><li>Word2Vec → Learning Relationships</li><li>GloVe → Global Relationships</li><li>FastText → Subword Understanding</li><li>BERT/GPT → Understanding meaning in Context</li></ol><h3>Final Insight</h3><p>From counting words…<br>To understanding meaning…<br>To understanding context…</p><p>Word embeddings completely changed how machines read language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f87117509301" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP for Beginners: How Machines Understand Text (Step-by-Step Guide)]]></title>
            <link>https://medium.com/@damodaran.selvaraj/nlp-for-beginners-how-machines-understand-text-step-by-step-guide-aa858d559458?source=rss-b50764aaf4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa858d559458</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Damodaran Selvaraj]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 12:31:01 GMT</pubDate>
            <atom:updated>2026-04-16T12:31:01.638Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn Natural Language Processing (NLP) using NLTK with a complete text preprocessing pipeline explained in simple terms</h4><blockquote>Raw text is messy. Machines hate messy data.<br>This guide shows how we clean, process, and transform text into something machines can actually understand.</blockquote><p>Have you ever wondered how machines understand human language?</p><p>From Google Translate to ChatGPT, modern AI systems rely on <strong>Natural Language Processing (NLP)</strong> to read, understand, and generate text.</p><p>In this beginner-friendly guide, you’ll learn <strong>NLP, NLTK, and text preprocessing step-by-step</strong>, with simple explanations and practical examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*91T8YMerws6frgEx-jtdag.png" /><figcaption>AI generated image</figcaption></figure><h3>What is NLP (Natural Language Processing)?</h3><p><strong>Natural Language Processing (NLP)</strong> is a branch of AI that helps computers understand, interpret, and generate human language.</p><p>In simple words:</p><blockquote>It allows machines to read, understand, and respond to text like humans do.</blockquote><h3>NLP is divided into two main parts</h3><h4>1. Natural Language Understanding (NLU)</h4><ul><li>Focuses on <strong>understanding meaning</strong></li><li>Example: Understanding sentiment, intent, context</li></ul><h4>2. Natural Language Generation (NLG)</h4><ul><li>Focuses on <strong>generating text</strong></li><li>Example: Chatbots, text summarization, AI writing tools</li></ul><h3>Popular NLP Libraries in Python</h3><p>Some beginner-friendly NLP libraries include:</p><ul><li><strong>NLTK (Natural Language Toolkit)</strong></li><li>spaCy</li><li>Gensim</li><li>TextBlob</li></ul><h3>What is <strong>NLTK (Natural Language Toolkit) in Python</strong>?</h3><p><strong>NLTK (Natural Language Toolkit)</strong> is one of the most popular Python libraries for NLP.</p><p>It helps you:</p><ul><li>Process text</li><li>Analyze language</li><li>Extract meaning from text data</li></ul><p>It is widely used for:</p><ul><li>Text analytics</li><li>Computational linguistics</li><li>Learning NLP fundamentals</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wV1cx1G8MZ8CEGOVTdqPqA.png" /><figcaption>AI generated Image</figcaption></figure><h4>What is ‘punkt’ in NLTK?</h4><p>When you see:</p><pre>nltk.download(&#39;punkt&#39;)</pre><p>It downloads a <strong>pre-trained tokenizer model. </strong>It helps Python split text into <strong>sentences or words.</strong></p><h3>Core NLP Tasks using NLTK</h3><p>NLTK makes it easy to perform:</p><ul><li>Tokenization</li><li>Stemming &amp; Lemmatization</li><li>POS Tagging</li><li>Parsing</li><li>Named Entity Recognition (NER)</li><li>Semantic analysis</li></ul><h3>NLP Pipeline Explained</h3><p>To understand how everything connects, here’s a simple NLP pipeline:</p><pre>Raw Text<br>↓<br>Text Normalization (lowercase, remove symbols)<br>↓<br>Tokenization (split into words/sentences)<br>↓<br>Stopword Removal<br>↓<br>Stemming / Lemmatization<br>↓<br>Feature Extraction (Vectorization)<br>↓<br>Machine Learning Model</pre><p>Each step improves the quality of text before it reaches the model.</p><p>This pipeline is the backbone of almost every NLP system.</p><h3>Text Preprocessing in NLP</h3><p>Before feeding text into models, we must <strong>clean and prepare it</strong>. This step is called <strong>data preprocessing</strong>.</p><h3>1) Text Normalization</h3><p>Before breaking text into tokens, we first clean and standardize it. This process is called <strong>text normalization</strong>.</p><p>In real-world data, text can be messy — it may contain uppercase letters, punctuation, numbers, or special characters. Normalization ensures consistency.</p><h4>Common Steps:</h4><ul><li>Convert text to lowercase</li><li>Remove punctuation</li><li>Remove numbers</li><li>Remove special characters</li><li>Remove extra spaces</li></ul><p><strong>Example:</strong></p><pre>import re</pre><pre>text = &quot;Hello!!! NLP 2025 is AMAZING :)&quot;<br>clean_text = re.sub(r&#39;[^a-zA-Z\s]&#39;, &#39;&#39;, text.lower())<br>print(clean_text)<br># Output:<br># hello nlp is amazing</pre><p>This step makes the text <strong>clean, uniform, and ready for further processing</strong></p><h3>2) Tokenization in NLP</h3><p>Tokenization refers to breaking down the text into smaller units. It splits paragraphs into sentences and sentences into words.</p><blockquote>Breaks text into smaller pieces so machines can process it</blockquote><h4><strong>2.1 Word Tokenization</strong></h4><p>Split text into individual words.</p><pre>from nltk.tokenize import word_tokenize, sent_tokenize</pre><pre>text = (<br>    &quot;Dam lives in Tamil Nadu, India. &quot;<br>    &quot;He studies NLP using NLTK. &quot;<br>    &quot;Natural language processing is interesting!&quot;<br>)<br><br>#Break into words<br>tokens = word_tokenize(text)<br>print(&quot;Words:&quot;, tokens)</pre><p>Output:</p><pre>[&#39;Dam&#39;, &#39;lives&#39;, &#39;in&#39;, &#39;Tamil&#39;, &#39;Nadu&#39;, &#39;,&#39;, &#39;India&#39;, &#39;.&#39;, ...]</pre><h4><strong>2.2 Sentence Tokenization</strong></h4><p>Breaking down the text into individual sentences.</p><pre>#Break into sentences<br>sentences = sent_tokenize(text)<br>print(&quot;Sentences:&quot;, sentences)</pre><p>Output:</p><pre>[<br>&quot;Dam lives in Tamil Nadu, India.&quot;,<br>&quot;He studies NLP using NLTK.&quot;,<br>&quot;Natural language processing is interesting!&quot;<br>]</pre><h3>3) Stemming vs Lemmatization</h3><p>These techniques reduce words to their base form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AK-w0xxwha_pJTp53grQNg.png" /><figcaption>AI generated Image</figcaption></figure><h4><strong>3.1 Stemming</strong></h4><ul><li>Removes suffixes (rules-based)</li><li>May not produce real words</li></ul><p>Example:</p><ul><li>running → run</li><li>studies → studi</li></ul><p>Key point:</p><ul><li>Fast but less accurate</li><li>Ignores context</li></ul><h4>3.2 Lemmatization</h4><ul><li>Converts words to <strong>dictionary form (lemma)</strong></li></ul><p>Example:</p><ul><li>running → run</li><li>better → good</li></ul><p>Key point:</p><ul><li>More accurate</li><li>Considers context</li></ul><h3>4) Part-of-Speech (POS) Tagging</h3><p>POS tagging identifies the <strong>grammar role</strong> of each word. The process of labeling words in a sentence with their corresponding grammatical roles such as nouns, verbs, adjectives, or adverbs based on context.</p><p><strong>Example:</strong></p><p>Sentence:<br> <em>“The quick brown fox jumps over the lazy dog.”</em></p><p>After POS tagging:</p><ul><li>The → Determiner (DT)</li><li>quick → Adjective (JJ)</li><li>brown → Adjective (JJ)</li><li>fox → Noun (NN)</li><li>jumps → Verb (VBZ)</li><li>over → Preposition (IN)</li><li>lazy → Adjective (JJ)</li><li>dog → Noun (NN)</li></ul><p>This helps machines understand <strong>sentence structure</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qGXzzdrRgCT0HJ777Uc95A.png" /><figcaption>AI generated Image</figcaption></figure><h3>5) Named Entity Recognition (NER)</h3><p>NER identifies and classifies important real-world entities such as people, locations, and organizations.</p><p><strong>Example:</strong></p><p>From a sentence, it can detect:</p><ul><li>Person names</li><li>Locations</li><li>Organizations</li></ul><p>Example:<br> “Dam lives in Tamil Nadu”</p><ul><li>Dam → Person</li><li>Tamil Nadu → Location</li></ul><h3>6) Removing Stopwords</h3><p>Stopwords are common words like:</p><blockquote><strong>is, the, in, a, and</strong></blockquote><p>These words don’t add much meaning or semantic value to text analysis which includes articles, prepositions and pronouns</p><p><strong>Example Code</strong></p><pre>from nltk.corpus import stopwords<br>from nltk.tokenize import word_tokenize<br>import nltk</pre><pre><br>nltk.download(&#39;stopwords&#39;)<br># Sample text<br>text = &quot;This is a sample sentence showing stopword removal.&quot;<br># Get English stopwords and tokenize<br>stop_words = set(stopwords.words(&#39;english&#39;))<br><br>tokens = word_tokenize(text.lower())<br># Remove stopwords<br>filtered_tokens = [word for word in tokens if word not in stop_words]<br><br>print(&quot;Original:&quot;, tokens)<br>print(&quot;Filtered:&quot;, filtered_tokens)</pre><p><strong>Output:</strong></p><pre>Original: [&#39;this&#39;, &#39;is&#39;, &#39;a&#39;, &#39;sample&#39;, &#39;sentence&#39;, &#39;showing&#39;, &#39;stopword&#39;, &#39;removal&#39;, &#39;.&#39;]<br>Filtered: [&#39;sample&#39;, &#39;sentence&#39;, &#39;showing&#39;, &#39;stopword&#39;, &#39;removal&#39;, &#39;.&#39;]</pre><h3>Limitations of NLTK</h3><p>While NLTK is great for learning and understanding NLP concepts, it has some limitations:</p><ul><li>Slower compared to modern libraries like spaCy</li><li>Requires more manual coding for advanced tasks</li><li>Not optimized for production-level applications</li><li>Limited support for deep learning workflows</li></ul><p>NLTK is best for <strong>education and experimentation</strong>, not large-scale production systems</p><h3>Why Preprocessing Matters</h3><p>Raw text is messy.</p><p>Preprocessing helps:</p><ul><li>Remove noise</li><li>Standardize text</li><li>Improve model accuracy</li><li>Reduce computation</li></ul><p>Without preprocessing, NLP models perform poorly.</p><h3>Frequently Asked Questions (FAQs)</h3><h4>What is NLP in simple words?</h4><p>Natural Language Processing (NLP) is a field of artificial intelligence that helps computers understand, interpret, and generate human language.</p><h4>What is NLTK used for?</h4><p>NLTK (Natural Language Toolkit) is a Python library used for text processing tasks such as tokenization, stemming, lemmatization, and linguistic analysis.</p><h4>What is text preprocessing in NLP?</h4><p>Text preprocessing is the process of cleaning and preparing raw text data before feeding it into machine learning models. It includes steps like normalization, tokenization, and stopword removal.</p><h4>Why is preprocessing important in NLP?</h4><p>Preprocessing improves data quality by removing noise and standardizing text, which helps machine learning models perform better and more accurately.</p><h4>What is tokenization in NLP?</h4><p>Tokenization is the process of breaking text into smaller units such as words or sentences so that machines can process it easily.</p><h4>What is the difference between stemming and lemmatization?</h4><p>Stemming removes word endings using simple rules and may produce incorrect words, while lemmatization converts words into their correct base (dictionary) form using context.</p><h4>What are stopwords in NLP?</h4><p>Stopwords are common words like “is”, “the”, and “in” that carry little meaning and are often removed during preprocessing to improve model performance.</p><h4>What is POS tagging in NLP?</h4><p>Part-of-Speech (POS) tagging is the process of labeling words in a sentence with their grammatical roles, such as noun, verb, or adjective.</p><h4>What is Named Entity Recognition (NER)?</h4><p>NER is a technique used to identify and classify important entities in text, such as names of people, locations, and organizations.</p><h4>What is text vectorization in NLP?</h4><p>Text vectorization is the process of converting text into numerical format so that machine learning models can understand and process it.</p><h4>Is NLTK good for beginners?</h4><p>Yes, NLTK is one of the best libraries for beginners to learn NLP concepts due to its simplicity and educational focus.</p><h4>What are the limitations of NLTK?</h4><p>NLTK is slower compared to modern libraries like spaCy, requires more manual coding, and is not ideal for production-level applications.</p><h4>Can NLP work without preprocessing?</h4><p>Technically yes, but performance will be poor because raw text contains noise and inconsistencies that confuse machine learning models.</p><h3>What Happens After Preprocessing?</h3><p>So far, we cleaned and structured the text.</p><p>But there’s a problem:</p><blockquote>Machines <strong>do not understand words, they understand numbers.</strong></blockquote><p>So how do we convert text into numbers? This is where <strong>Text Vectorization</strong> comes in.</p><p>It transforms text into numerical format so that machine learning models can process it.</p><p>Some common techniques:</p><ul><li>Bag of Words (BoW)</li><li>TF-IDF</li><li>Word Embeddings (Word2Vec, GloVe, Fasttext)</li></ul><p>In the next post, we will dive deep into how text becomes numbers and how models actually “understand” language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa858d559458" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recurrent Neural Networks (RNNs) Explained]]></title>
            <link>https://medium.com/@damodaran.selvaraj/recurrent-neural-networks-rnns-explained-55f417f79163?source=rss-b50764aaf4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/55f417f79163</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[gru]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Damodaran Selvaraj]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 17:58:31 GMT</pubDate>
            <atom:updated>2026-04-14T18:05:32.525Z</atom:updated>
            <content:encoded><![CDATA[<p>When we first learn about neural networks, most examples treat data as if every input is completely independent. For example, if you give an image to a neural network, it processes that image and gives an output — and that’s it. It doesn’t care about what came before or after.</p><p>But in real life, most data is not like that.</p><p>Think about how you read a sentence. If I say:</p><blockquote><em>“I went to the bank to deposit money”</em></blockquote><p>you understand that <em>bank</em> means a financial place, not a riverbank. But how did you know that? Because of the words that came before it.</p><p>This is exactly the kind of problem that <strong>Recurrent Neural Networks (RNNs)</strong> are designed to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LU3l82_l-0jMPLXPL9V9Vg.png" /><figcaption>AI generated Image</figcaption></figure><h4>What Exactly is an RNN and Why Do We Need It?</h4><p>A <strong>Recurrent Neural Network (RNN)</strong> is a type of neural network that is built to handle <strong>sequential data</strong> — data where <strong>order matters</strong>.</p><blockquote>RNNs process data step-by-step while carrying forward information from previous steps, allowing them to understand context over time.</blockquote><p>In short:</p><blockquote>RNN = “Neural network with memory”</blockquote><h4>How RNN Works (step-by-step)</h4><p>Let’s break it down simply.</p><p><strong>Step 1: Input comes one by one</strong></p><p>Example sentence:</p><blockquote>“I love machine learning”</blockquote><p>The RNN reads it like:</p><ul><li>“I” → then</li><li>“love” → then</li><li>“machine” → then</li><li>“learning”</li></ul><p><strong>Step 2: It remembers previous words</strong></p><p>At each step, RNN keeps a <strong>hidden state</strong> (memory)</p><p>So:</p><ul><li>At “love” → it remembers “I”</li><li>At “machine” → it remembers “I love”</li><li>At “learning” → it remembers full context</li></ul><p><strong>Step 3: It updates memory continuously</strong></p><p>The memory gets updated like this:</p><pre>New Memory = (Previous Memory + Current Input)</pre><p>So it always carries forward context.</p><blockquote><strong>Hidden state update:<br> hₜ = f(hₜ₋₁, xₜ)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*8dF1x7Y2irIyJ-N9WgqKjw.png" /></figure><h4>Why the Word ‘Recurrent’ Actually Matters?</h4><p>Because the same process repeats again and again.</p><ul><li>Same network</li><li>Same weights</li><li>Used at every time step</li></ul><p>Like a loop.</p><h4>Types of RNN Architectures</h4><p><strong>1. One-to-One — </strong>Normal neural network</p><p><strong>2. One-to-Many — </strong>Image → Caption</p><p><strong>3. Many-to-One — </strong>Sentiment analysis</p><p><strong>4. Many-to-Many — </strong>Translation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hjjcEsK4GWjTLQ2ZuMo14w.png" /></figure><h4>Real-Life Use Cases of RNN</h4><p>RNNs are powerful when <strong>sequence matters</strong>:</p><p><strong>1. Speech Recognition</strong></p><p>Convert speech → text<br>Example: “Hey Siri”, “Ok Google”</p><p><strong>2. Text Prediction (Autocomplete)</strong></p><p>Typing:</p><blockquote>“How are y…”</blockquote><p>RNN predicts:</p><blockquote>“you?”</blockquote><p><strong>3. Machine Translation</strong></p><p>Translate:</p><ul><li>English → Tamil</li><li>English → French</li></ul><p><strong>4. Time Series Prediction</strong></p><ul><li>Stock prices</li><li>Weather forecasting</li></ul><p><strong>5. Chatbots</strong></p><p>Understand conversation flow over time</p><h4>The Core Idea (in one line)</h4><blockquote><em>RNN doesn’t just look at the current input — it also remembers the past.</em></blockquote><h4>Backpropagation Through Time (BPTT)</h4><p>This memory mechanism allows RNNs to capture temporal dependencies across sequences. During training, RNNs do not update weights based only on the current time step t. Instead, they consider all <strong>previous time steps</strong> <strong>t−1, t−2, t−3,… </strong>This training process is called <strong>Backpropagation Through Time (BPTT). </strong>The idea is to “unroll” the network across all time steps and then compute gradients through this unrolled graph.</p><p>However, this is where RNNs famously struggle. When gradients are propagated back through many time steps, they can:</p><ul><li><strong>Vanish</strong> — become exponentially small, making it impossible to learn long-range dependencies. The network “forgets” what happened many steps ago.</li><li><strong>Explode</strong> — grow exponentially large, destabilising training. Gradient clipping is the standard fix.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G7hqw00CTTVHH6-pUzlkug.png" /><figcaption>AI generated Image</figcaption></figure><h3>Variants of Recurrent Neural Networks (RNNs)</h3><p>There are several variations of RNNs, each designed to address specific challenges or optimize for certain tasks:</p><h4>1. Vanilla RNN</h4><p>This simplest form of RNN consists of a single hidden layer where weights are shared across time steps. Vanilla RNNs are suitable for learning short-term dependencies but are limited by the vanishing gradient problem, which hampers long-sequence learning.</p><h4>2. Bidirectional RNNs</h4><p>Bidirectional RNNs process inputs in both forward and backward directions, capturing both past and future context for each time step. This architecture is ideal for tasks where the entire sequence is available, such as named entity recognition and question answering.</p><h4>3. Long Short-Term Memory Networks (LSTMs)</h4><p>Long Short-Term Memory Networks (LSTMs) introduce a memory mechanism to overcome the vanishing gradient problem. Each LSTM cell has three gates:</p><p><strong>Input Gate:</strong> Controls how much new information should be added to the cell state.<br><strong>Forget Gate: </strong>Decides what past information should be discarded.<br><strong>Output Gate:</strong> Regulates what information should be output at the current step. This selective memory enables LSTMs to handle long-term dependencies, making them ideal for tasks where earlier context is critical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwPEbpH5WRC3yShWk_ERig.png" /><figcaption>AI generated Image</figcaption></figure><h4>4. Gated Recurrent Units (GRUs)</h4><p>Gated Recurrent Units (GRUs) simplify LSTMs by combining the input and forget gates into a single update gate and streamlining the output mechanism. This design is computationally efficient, often performing similarly to LSTMs and is useful in tasks where simplicity and faster training are beneficial.</p><h4>Why RNNs Changed Machine Learning Forever?</h4><p>Recurrent Neural Networks were a major step forward in machine learning because they introduced the idea of <strong>memory</strong> into neural networks.</p><blockquote><strong>RNNs taught machines something fundamental:<br>Understanding the present requires remembering the past.</strong></blockquote><blockquote><strong>And that idea still powers modern AI today.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55f417f79163" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>