<?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"><channel><title><![CDATA[krypticmouse]]></title><description><![CDATA[ML Engineer @Simplified | Chill @CreworkHQ | Ex-ML @CrowdANALYTIX_q | @DRDO_India | Loves ML and Mangas]]></description><link>https://krypticmouse.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1619641458812/RpN_hzmke.png</url><title>krypticmouse</title><link>https://krypticmouse.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 15 Nov 2026 03:24:10 GMT</lastBuildDate><atom:link href="https://krypticmouse.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Writing a Compiler in Rust #1: Lexical Analysis]]></title><description><![CDATA[Compilers are not a game of luck. If you want it to work, code hard. - Sora (No Game No Life) Another blog, another butchered quote but what matters is…]]></description><link>https://krypticmouse.hashnode.dev/writing-a-compiler-lexical-analysis</link><guid isPermaLink="true">https://krypticmouse.hashnode.dev/writing-a-compiler-lexical-analysis</guid><category><![CDATA[Computer Science]]></category><category><![CDATA[compiler]]></category><category><![CDATA[Rust]]></category><category><![CDATA[technology]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Herumb Shandilya]]></dc:creator><pubDate>Fri, 02 Feb 2024 08:09:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706219797890/6acb96bf-4bcc-4505-8025-b4ea6a89a3bd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Compilers are not a game of luck.</p>
<p>If you want it to work, code hard.</p>
<p>- Sora (No Game No Life)</p>
</blockquote>
<p>Another blog, another butchered quote but what matters is that they never created a season 2 for this series and I'm max pissed about it!! Anyways, as someone who has a Computer Science Degree, it's a bit shameful for me to admit that I never formally studied compilers, well in my defense it's because it was an elective and I chose an ML elective instead of Compiler Design. Although it is something that I've always enjoyed hearing a lot about.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706220084249/579080b9-c333-492f-acb1-1b33e10462a4.gif" alt class="image--center mx-auto" /></p>
<p>Recently this shame took over me and I decided to learn it again and I was surprised how simple and elegant this was!! Not just that I feel that LLMs and compilers are kinda same in terms of how they break down their end-to-end pipeline. But that's enough rambling for now and let's start understanding compilers!!!</p>
<h2 id="heading-wtf-is-a-compiler">WTF is a Compiler?</h2>
<p>I'm gonna assume most of you have some experience in writing code in some programming language, if you don't you should probably learn one first <strong>😅</strong>. In programming what we do is that we write a <strong>syntax to define a logic</strong>. This logic could be as simple as adding two numbers or as complicated as writing the backend for a product.</p>
<p>Regardless of the logic or program you are building, you are working around the same syntax for whatever programming language you choose. For the most part, most programming languages share the <strong>same semantics but differ in syntax</strong>. What that means is the syntax for defining a <em>for loop</em> might differ across different languages but the core meaning and use case of <em>for loop</em> remains the same.</p>
<p>A Compiler helps the machine understand the semantics of the program from the given syntax. What it does is take the high-level source code that is written in a language like C, C++, Rust, etc., and convert it into low-level machine code that the computer processor can understand and execute. How does a compiler do this anyway?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706216644697/2a6ae6c4-8a65-45e5-a85c-a65e24d0d0e7.png" alt class="image--center mx-auto" /></p>
<p>The compiler takes the code you wrote as input, to a compiler your code is just a big string. So to make the machine understand it the compiler transforms it multiple times across multiple steps and converts it to a machine language like assembly that the computer can understand and execute. To elaborate more these steps are:</p>
<ul>
<li><p><strong>Lexical Analysis:</strong> The source code is broken down into tokens - things like keywords, identifiers, operators, separators, etc.</p>
</li>
<li><p><strong>Parsing or Syntax Analysis:</strong> The tokens are analyzed to see if they follow the rules of the language. This ensures the code is syntactically correct.</p>
</li>
<li><p><strong>Semantic Analysis:</strong> The meaning of the code is analyzed to catch any logical errors. Things like type-checking happen here.</p>
</li>
<li><p><strong>Intermediate Code Generation:</strong> The code is converted into an intermediate representation, often in the form of assembly code or bytecode.</p>
</li>
<li><p><strong>Code Optimization:</strong> The intermediate code is optimized to improve efficiency - common optimizations include removing redundant or unused code.</p>
</li>
<li><p><strong>Code Generation:</strong> The optimized intermediate code is translated into the target machine code for the specific CPU architecture.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706217098166/ff2a5d45-97cf-4c52-88fc-859fe3a8872b.png" alt class="image--center mx-auto" /></p>
<p>In this article, we'll be covering step one which is <strong>Lexical Analysis,</strong> and implement a very basic lexer. To implement this lexer I'll be choosing Rust as my language of choice because I'm trying to build my expertise in it so...sorry in advance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706212688903/580eb300-af39-4c83-b3ae-7e0708df3e64.png" alt class="image--center mx-auto" /></p>
<p>But by the end of this blog, we'll know how to build our own lexer from scratch!! But wait, what's a lexer? Let's learn.</p>
<h2 id="heading-what-is-lexical-analysis">What is Lexical Analysis?</h2>
<p><em>Lexical Analysis</em> is the first step in almost all compilers, it involves taking your code as input and receiving a set of tokens that defines the meaning of each word in the code. These words are called <strong>lexemes</strong> and we'll dive more into what makes a lexeme, a lexeme.</p>
<p>But for now, we should understand that in the lexical analysis, we are taking the program as input and getting a token per lexeme as the output. All this process is done via a lexer which is basically just a set of code.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706292949508/d3d014a6-84d3-4129-ab67-cf521917ab87.png" alt class="image--center mx-auto" /></p>
<p>Let's take an example code to understand exactly what lexer processes and returns. Take the following Python code as example:</p>
<pre><code class="lang-python">a = <span class="hljs-number">10</span> <span class="hljs-keyword">if</span> <span class="hljs-number">10</span>&lt;<span class="hljs-number">12</span> <span class="hljs-keyword">else</span> <span class="hljs-number">12</span>
</code></pre>
<p>If we pass the above code as input to the lexer it'll return something like this:</p>
<pre><code class="lang-plaintext">[IDENTIFIER, 'a']  [ASSIGN_OP, '=']  [INTEGER, '10']  [IF]  [INTEGER, '10']  [LESS_THAN]  [INTEGER, '12']  [ELSE]  [INTEGER, '12']
</code></pre>
<p>So the lexer looks at each lexeme (word/symbol) in the code and categorizes it into a token type. Identifiers or variables become <code>IDENTIFIER</code> tokens, integer literals become <code>INT_LITERAL</code> tokens, operators and delimiters get their token types, etc.</p>
<p>This tokenization is important because it standardizes the vocabulary of the code so the later compiler steps can reliably recognize constructs regardless of identifier names or literal values chosen by the programmer.</p>
<p>The lexer often "ignores" characters like whitespace and comments and just focuses on the necessary lexemes. To be more clear, the lexer knows the presence of whitespace but it decides to discard it. But in indentation-sensitive languages like Python, things can be different and whitespace might not be discarded.</p>
<p>But how do we do this? How do we take a set of lexemes and identify their tokens? Let's learn.</p>
<h2 id="heading-regular-language">Regular Language</h2>
<p>The syntax of a language is represented via something called Regular Language. You can think of Regular Language as the rules of a programming language that defines the syntax of the language.</p>
<p>For example, in English we can make many words but not all those words are classified as <strong>language</strong>, so we know "book" is a valid word in the language but "dsfdnf" is not even though both use alphabets. Same way in programming languages, we can write anything but not every program can be said to be a part of that language. Look at the code below:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">if</span> a===b{
    <span class="hljs-keyword">return</span> a;
}
</code></pre>
<p>The above code can be valid for Javascript but not C++ because in JS <code>===</code> can be treated as <code>EQUAL_TO</code> token but in C++ it'll be <code>EQUAL_TO ASSIGN</code> token which will be an invalid operation.</p>
<p>To define these rules or Regular Language we use something called Regular Expressions or RegEx. NLP folks might've had some experience with regex in one way or the other. But if you haven't no worries, your boy has got you covered.</p>
<h2 id="heading-regular-expression">Regular Expression</h2>
<p>A regular expression (or regex) is a way of describing a pattern of characters that can be used to match against a piece of text. They can be used to define the rules for a regular language, and then a compiler can use those rules to analyze a piece of source code and determine whether it is a valid instance of the language.</p>
<p>Think like this the syntax for variable declaration, keywords, etc. All have a pattern for keywords you have a finite set of them that you need to match, for variables or identifiers you have a rule that the name of the variable must start with a letter which is followed by a letter or a digit.</p>
<p>Now writing a Regex string has some rules those are:</p>
<ul>
<li><p><strong>Start and End Anchors</strong>: <code>^</code> and <code>$</code> are used to denote the beginning and end of a line, respectively. <code>^</code> matches the position before the first character in the string, and <code>$</code> matches the position after the last character in the string.</p>
</li>
<li><p><strong>Character Classes</strong>: <code>[ ]</code> are used to match any one of the characters enclosed within the brackets. For example, <code>[abc]</code> will match any single 'a', 'b', or 'c'. Ranges can also be specified, like <code>[a-z]</code> for any lowercase letter and [0-9] for any digit.</p>
</li>
<li><p><strong>Predefined Character Classes</strong>: These are shortcuts for common character classes. For instance, <code>\d</code> matches any digit (equivalent to <code>[0-9]</code>), <code>\w</code> matches any word character (equivalent to <code>[a-zA-Z0-9_]</code>), and <code>\s</code> matches any whitespace character (like space, tab, newline).</p>
</li>
<li><p><strong>Negated Character Classes</strong>: Placing a <code>^</code> inside square brackets negates the class. For example, <code>[^abc]</code> matches any character except 'a', 'b', or 'c'.</p>
</li>
<li><p><strong>Quantifiers</strong>: These specify how many instances of a character or group are needed for a match. <code>*</code> matches zero or more, <code>+</code> matches one or more, <code>?</code> matches zero or one, and <code>{n}</code>, <code>{n,}</code>, <code>{n,m}</code> are used for specific quantities.</p>
</li>
</ul>
<p>This syntax is usually the same for regex across any language, so this will apply to Rust, Python, or any other language. But theory can only take you so far, so let's start implementing the lexer and building regex for every keyword, identifier, operation etc.</p>
<h2 id="heading-implementing-the-lexer">Implementing the Lexer</h2>
<p>So it's time to take a deep dive into Building the Lexer for our Compiler, I think we'll call our compiler <strong>BitterByte</strong> that sounds cool af!! Let's call it that from now on!! So our goal is to compile the following code:</p>
<pre><code class="lang-javascript">int x = <span class="hljs-number">5</span>;
int y = <span class="hljs-number">6</span>;
int z = x + y;

<span class="hljs-keyword">if</span> (z &gt; <span class="hljs-number">10</span>) {
    print(<span class="hljs-string">"Hello, world!"</span>);
} 

<span class="hljs-keyword">else</span> {
    print(<span class="hljs-string">"Goodbye, world!"</span>);
}
</code></pre>
<p>Based on that we need a lexer that can capture: keywords (<code>int</code>, <code>if</code>, <code>else</code>), identifiers (<code>x</code>, <code>y</code>, <code>z</code>), numbers (<code>5</code>, <code>6</code>, <code>10</code>), operators (<code>=</code>, <code>+</code>, <code>&gt;</code>), punctuation (<code>;</code>, <code>(</code>, <code>)</code>, <code>{</code>, <code>}</code>), and strings (<code>"Hello, world!"</code>, <code>"Goodbye, world!"</code>).</p>
<p>Ohhh this is gonna be fun!! I know many of you won't have experience in E\Rust but if you do that'll be great but I'll be giving you some explanation on the code regardless. All the code can be found in the repository <a target="_blank" href="https://github.com/krypticmouse/rust-compiler"><strong>here</strong></a>. Let's gooo!!</p>
<h3 id="heading-initializing-our-project">Initializing our Project</h3>
<p>So we'll need to start creating our project directory with Rust stuff all set. For this, we'll be using cargo which is the package manager, and build system for Rust. Unlike Python, Rust is a compiled language which means you compile the Rust code first before you execute it.</p>
<p>Cargo takes of the compilation, execution, and package management in Rust. We can also use it to initialize our rust project too, kinda like <code>create-next-app</code>. Let's initialize our project <code>rust-compiler</code>:</p>
<pre><code class="lang-plaintext">cargo new rust-compiler
cd rust-compiler
</code></pre>
<p>Pretty simple right? In this directory, you'll find a file with a weird extension and a <code>src</code> directory which is a pretty big deal. Overall the initial repo structure would look like this:</p>
<pre><code class="lang-plaintext">.
├── Cargo.toml
├── src
│   └── main.rs
</code></pre>
<p>What are these files and directories you wonder? Let me explain:</p>
<ol>
<li><p><strong>Cargo.toml</strong>: This is the configuration file for your project. It includes metadata about your project like the name, version, authors, dependencies, and more. It's kinda like <code>package.json</code> React.js or <code>pyproject.toml</code> in Python Poetry. If you need to include a package simply drop it here!</p>
</li>
<li><p><strong>src/</strong><a target="_blank" href="http://main.rs"><strong>main.rs</strong></a>: This is the default entry point of your Rust program. When you run or build your Rust code, Cargo looks for this file to compile your project as a binary.</p>
</li>
</ol>
<p>While this initial structure gives us a good starting point to start our project, we'll be elegant and populate it with more files in <code>src</code> directory to organize it. And trust me when I say it...it's hard to be elegant in Rust without losing your mind.</p>
<p><img src="https://preview.redd.it/good-for-you-crab-v0-5v9ygeh9r1c91.jpg?width=640&amp;crop=smart&amp;auto=webp&amp;s=13e79c30adb04181782c462f07a95bc343d73eaf" alt="Good for you Crab : r/ProgrammerHumor" class="image--center mx-auto" /></p>
<h3 id="heading-understanding-repo-structure">Understanding Repo Structure</h3>
<p>Now that we have an initial repo structure we can go ahead and populate it with files we'll be working with. In this tutorial, we are building a lexer so we'll create a subfolder in <code>src</code> by the name <code>lexing</code>:</p>
<pre><code class="lang-plaintext">cd src
mkdir lexing
</code></pre>
<p>In <code>lexing</code> we'll add 3 files: <code>token.rs</code>, <code>lexer.rs</code> and <code>mod.rs</code>. We'll understand what each of these files will contain but for now, this is what your repo structure should look like:</p>
<pre><code class="lang-plaintext">.
├── Cargo.toml
├── src
│   ├── lexing
│   │   ├── lexer.rs
│   │   ├── mod.rs
│   │   └── token.rs
│   └── main.rs
</code></pre>
<p>Before diving into writing code we'll need to let Cargo know that we're using <strong>regex</strong> library crate too!! To do that we edit the <code>Cargo.toml</code> and add regex library crate in it:</p>
<pre><code class="lang-plaintext">[package]
name = "rust-compiler"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
regex="1" # Added this
</code></pre>
<p>The "1" tells cargo to use the latest package of <code>regex</code> but you can be more specific and write the exact version of the package too. I'm lazy so I won't do that, deal with it.</p>
<p><img src="https://images7.memedroid.com/images/UPLOADED8/545fdf490d891.jpeg" alt="Deal with it - Meme by arthurkaly :) Memedroid" class="image--center mx-auto" /></p>
<p>Now that we have our files populated it's time to fill them up with code!!</p>
<h3 id="heading-writing-tokenrs">Writing token.rs</h3>
<p>So, let's start by implementing the tokens for our lexer, for this, we'll be using enums in Rust which are best suited for this task. We'll be creating an enum <code>Token</code> which will hold the token type for lexemes:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Token</span></span>{
    <span class="hljs-comment">// Keywords</span>
    Print(<span class="hljs-built_in">String</span>),
    If(<span class="hljs-built_in">String</span>),
    Else(<span class="hljs-built_in">String</span>),
    Int(<span class="hljs-built_in">String</span>),

    <span class="hljs-comment">// Literals</span>
    IntegerLiteral(<span class="hljs-built_in">i32</span>),
    StringLiteral(<span class="hljs-built_in">String</span>),

    <span class="hljs-comment">// Identifiers</span>
    Identifier(<span class="hljs-built_in">String</span>),

    <span class="hljs-comment">// Operators</span>
    Plus(<span class="hljs-built_in">String</span>),
    Assign(<span class="hljs-built_in">String</span>),

    <span class="hljs-comment">// Punctuation</span>
    Semicolon(<span class="hljs-built_in">String</span>),
    LeftParen(<span class="hljs-built_in">String</span>),
    RightParen(<span class="hljs-built_in">String</span>),
    LeftBrace(<span class="hljs-built_in">String</span>),
    RightBrace(<span class="hljs-built_in">String</span>),

    <span class="hljs-comment">// Logical Operators</span>
    GreaterThan(<span class="hljs-built_in">String</span>),
    LessThan(<span class="hljs-built_in">String</span>),
}
</code></pre>
<p>We've added the type for every possible token which seems to be fairly limited, in reality, this list can be much bigger! As you might have noticed most elements are of type <code>String</code>, this might not be the most optimal way to do this or something people call <strong>Idiomatic Rust</strong>.</p>
<p>But I used it to keep things simple and sane without needing to dwell on the issues of Generic Lifetimes. Trust me I'm not ready to explain and if you are new to Rust then there is a good chance you aren't ready to understand either.</p>
<p><img src="https://i.ytimg.com/vi/oD6U_2s0qdY/maxresdefault.jpg" alt class="image--center mx-auto" /></p>
<p>So yeah, there goes that!! This <code>#[derive(Debug)]</code> is not a comment, in Rust comments start with <code>//</code>. Rather it is an attribute that implements a trait called <code>Debug</code> which basically lets us print the enum elements <code>println!</code> without any extra effort. I know man, Rust is weird af. Moving on, we need to implement 2 functions:</p>
<ul>
<li><p>Given the <strong>token_type</strong> <strong>string</strong> and a <strong>value</strong>, return the token object. For example, given <strong>token_type string</strong> <code>"IntegerLiteral"</code> and <strong>value</strong> <code>300</code> it'll return us <code>Token::IntegerLiteral(300)</code> where <code>::</code> is used to specify a particular variant of an enum which in this case is <code>IntegerLiteral</code>.</p>
</li>
<li><p>Given the <strong>token_type</strong> string, return the regex to match the lexeme for that token type.</p>
</li>
</ul>
<p>Like we implement class methods in Python we can do something similar in Rust by using <code>impl</code>. So the above two functions can be implemented inside <code>impl</code> for <code>Token</code>, kinda it's their class method iykwim.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> Token {
    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_token</span></span>(token_type: &amp;<span class="hljs-built_in">str</span>, value: <span class="hljs-built_in">Option</span>&lt;&amp;<span class="hljs-built_in">str</span>&gt;) -&gt; Token {
        <span class="hljs-keyword">match</span> token_type {
            <span class="hljs-string">"Print"</span> =&gt; Token::Print(<span class="hljs-string">"print"</span>.to_string()),
            <span class="hljs-string">"If"</span> =&gt; Token::If(<span class="hljs-string">"if"</span>.to_string()),
            <span class="hljs-string">"Else"</span> =&gt; Token::Else(<span class="hljs-string">"else"</span>.to_string()),
            <span class="hljs-string">"Int"</span> =&gt; Token::Int(<span class="hljs-string">"int"</span>.to_string()),
            <span class="hljs-string">"IntegerLiteral"</span> =&gt; Token::IntegerLiteral(value.unwrap().parse::&lt;<span class="hljs-built_in">i32</span>&gt;().unwrap()),
            <span class="hljs-string">"StringLiteral"</span> =&gt; Token::StringLiteral(value.unwrap().to_string()),
            <span class="hljs-string">"Identifier"</span> =&gt; Token::Identifier(value.unwrap().to_string()),
            <span class="hljs-string">"Plus"</span> =&gt; Token::Plus(<span class="hljs-string">"+"</span>.to_string()),
            <span class="hljs-string">"Assign"</span> =&gt; Token::Assign(<span class="hljs-string">"="</span>.to_string()),
            <span class="hljs-string">"Semicolon"</span> =&gt; Token::Semicolon(<span class="hljs-string">";"</span>.to_string()),
            <span class="hljs-string">"LeftParen"</span> =&gt; Token::LeftParen(<span class="hljs-string">"("</span>.to_string()),
            <span class="hljs-string">"RightParen"</span> =&gt; Token::RightParen(<span class="hljs-string">")"</span>.to_string()),
            <span class="hljs-string">"LeftBrace"</span> =&gt; Token::LeftBrace(<span class="hljs-string">"{"</span>.to_string()),
            <span class="hljs-string">"RightBrace"</span> =&gt; Token::RightBrace(<span class="hljs-string">"}"</span>.to_string()),
            <span class="hljs-string">"GreaterThan"</span> =&gt; Token::GreaterThan(<span class="hljs-string">"&gt;"</span>.to_string()),
            <span class="hljs-string">"LessThan"</span> =&gt; Token::LessThan(<span class="hljs-string">"&lt;"</span>.to_string()),
            _ =&gt; <span class="hljs-built_in">panic!</span>(<span class="hljs-string">"Invalid token type: {}"</span>, token_type),
        }
    }

    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_token_regex</span></span>(token_type: &amp;<span class="hljs-built_in">str</span>) -&gt; <span class="hljs-built_in">String</span> {
        <span class="hljs-keyword">match</span> token_type {
            <span class="hljs-string">"Print"</span> =&gt; <span class="hljs-string">r"print"</span>,
            <span class="hljs-string">"If"</span> =&gt; <span class="hljs-string">r"if"</span>,
            <span class="hljs-string">"Else"</span> =&gt; <span class="hljs-string">r"else"</span>,
            <span class="hljs-string">"Int"</span> =&gt; <span class="hljs-string">r"int\s+"</span>,
            <span class="hljs-string">"IntegerLiteral"</span> =&gt; <span class="hljs-string">r"\d+"</span>,
            <span class="hljs-string">"StringLiteral"</span> =&gt; <span class="hljs-string">r#"\".*\""#</span>,
            <span class="hljs-string">"Identifier"</span> =&gt; <span class="hljs-string">r"[a-zA-Z_][a-zA-Z0-9_]* ="</span>,
            <span class="hljs-string">"Plus"</span> =&gt; <span class="hljs-string">r"\+"</span>,
            <span class="hljs-string">"Assign"</span> =&gt; <span class="hljs-string">r"="</span>,
            <span class="hljs-string">"Semicolon"</span> =&gt; <span class="hljs-string">r";"</span>,
            <span class="hljs-string">"LeftParen"</span> =&gt; <span class="hljs-string">r"\("</span>,
            <span class="hljs-string">"RightParen"</span> =&gt; <span class="hljs-string">r"\)"</span>,
            <span class="hljs-string">"LeftBrace"</span> =&gt; <span class="hljs-string">r"\{"</span>,
            <span class="hljs-string">"RightBrace"</span> =&gt; <span class="hljs-string">r"}"</span>,
            <span class="hljs-string">"GreaterThan"</span> =&gt; <span class="hljs-string">r"&gt;"</span>,
            <span class="hljs-string">"LessThan"</span> =&gt; <span class="hljs-string">r"&lt;"</span>,
            _ =&gt; <span class="hljs-built_in">panic!</span>(<span class="hljs-string">"Invalid token type: {}"</span>, token_type),
        }.to_string()
    }
}
</code></pre>
<p>As you can see we are basically doing a basic string matching here and returning the appropriate result based on whatever matches. <code>match</code> in Rust is pretty much similar to <code>switch-case</code> statements in C++ and Java.</p>
<p>Another thing you'll notice is <code>&amp;str</code> and <code>String</code> being used, well they are different in Rust and to convert a <code>&amp;str</code> to <code>String</code> we used <code>to_string</code>. For the sake of simplicity, you can think of <code>&amp;str</code> as an immutable string and <code>String</code> as a mutable string. I regret choosing Rust so bad!!</p>
<p>Lastly, you also see that the function panics if it doesn't match any regex this is what we'll call a <strong>Syntax Error</strong>. This is something we should never let happen, aside from keywords that <code>if</code> can be mistaken for an identifier too!! But since keywords are before identifier in the <code>match</code> statement or as people say in <strong>higher priority</strong> this issue would be avoided.</p>
<p>But what if we have an overlap b/w two 2 tokens, for example, if we have <code>int ifer = 10</code> here <code>if</code> is a keyword now but <code>ifer</code> is actually an identifier? In cases like this, we choose the regex which is bigger in size, this rule is called <strong>maximal munch</strong>. Which we'll implement as well in <code>lexer.rs</code>.</p>
<p>Now that we have the functions it's time to address the elephant in the room, "WTH are those weird strings in <code>get_token_regex</code> method???". Well, they are regex!!</p>
<p><img src="https://media.tenor.com/oak_Ivz3By8AAAAe/yeah-no-shit-william-zabka.png" alt="Yeah No Shit William Zabka GIF - Yeah No Shit William Zabka Johnny Lawrence  - Discover &amp; Share GIFs" class="image--center mx-auto" /></p>
<p>I know I know it seems like an alien language but let's learn more about it and how we built it!!</p>
<h3 id="heading-understanding-regex">Understanding Regex</h3>
<p>Regexes are essentially a set of rules or patterns defined by a string of characters, which can be used to search for specific text within a larger body of text, replace certain text patterns, or extract portions of a text that match a given pattern.</p>
<p>Let's understand with an example of an email validator. Email addresses typically follow a standard format: they start with a series of characters that can include letters, numbers, dots, underscores, or hyphens, followed by the <code>@</code> symbol, then more characters including letters and possibly dots, hyphens, or underscores, and finally a domain extension like <code>.com</code>, <code>.org</code>, etc.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706792046384/c8538e0e-076a-4cf2-bdf1-2779fd17f822.jpeg" alt class="image--center mx-auto" /></p>
<p>Now you can either write a 100-line code that validates this by manually verifying every case possible like <strong>@</strong> should be present, the part before <strong>@</strong> should start with a letter, should contain letters or digits and not any invalid character, etc. An easy way would be to use regex like <code>[a-zA-Z][a-zA-Z0-9]*@[a-zA-Z0-9]+.[com|org|net]</code>.</p>
<p>That string might look really weird right now so let's break that down a bit:</p>
<ul>
<li><p><code>[a-zA-Z]</code>: This bit is like saying, "Start by finding a letter." It doesn't matter if it's uppercase (A-Z) or lowercase (a-z), any letter will do. But, it's important that it's a letter, not a number or a symbol.</p>
</li>
<li><p><code>[a-zA-Z0-9]*</code>: After finding that first letter, this part says "Now, keep going and find any mix of letters (both upper or lowercase) and numbers (0-9)." The asterisk <code>*</code> at the end is a special "metacharacter", allowing for 0 or more of these characters.</p>
</li>
<li><p><code>@</code>: Next, we must find the <code>@</code> symbol. This is necessary for email addresses as it separates the user's name from their email domain.</p>
</li>
<li><p><code>[a-zA-Z0-9]+</code>: After the <code>@</code> symbol, we're looking for a string of letters and numbers again. This represents the domain name (like 'gmail' in 'user@gmail.com'). <code>+</code> at the end is another special "metacharacter", allowing for 1 or more of these characters.</p>
</li>
<li><p><code>.</code>: Then comes a literal dot. In email addresses, this dot separates the domain name from the domain extension.</p>
</li>
<li><p><code>(com|org|net)</code>: Finally, we're specifying that the email address must end with either '.com', '.org', or '.net'. The parentheses group 'com', 'org', and 'net' together as a single unit, and the <code>|</code> symbol acts as an "or." So, this part says, "Find either '.com', '.org', or '.net' right after the dot."</p>
</li>
</ul>
<p>You see how we simplified the whole thing to a regex string. Regex can help you validate a pattern but it can also help you find it!! If we pass <code>if</code> to regex it can return us a vector of starting and ending indexes of every occurrence of if in that string.</p>
<p><img src="https://media0.giphy.com/media/7pLv68ItwBaHS/giphy.gif?cid=6c09b952gjhqnj7eusw19m2tkgf0t84i60wsffhstd1laqp9&amp;ep=v1_gifs_search&amp;rid=giphy.gif&amp;ct=g" alt="Good-stuff-from-hacf GIFs - Get the best GIF on GIPHY" class="image--center mx-auto" /></p>
<h3 id="heading-writing-regex-for-tokens">Writing Regex for Tokens</h3>
<p>Based on whatever we learned now we can understand why we wrote the regex of each token the way we did. Let's see:</p>
<ol>
<li><p><strong>Keywords and Operators</strong></p>
<ul>
<li><code>r"print"</code>, <code>r"if"</code>, <code>r"else"</code>, <code>r"int\s+"</code>: These are straightforward. They match the specific keyword strings. For <code>int</code>, <code>\s+</code> is added to ensure there's at least one whitespace character after the keyword, differentiating it from identifiers that might start with "int" (like <code>integerValue</code>).</li>
</ul>
</li>
<li><p><strong>Literals</strong></p>
<ul>
<li><p><code>r"\d+"</code>: This pattern matches integer literals. <code>\d</code> represents any digit, and <code>+</code> means one or more of the preceding elements, so this matches a sequence of digits.</p>
</li>
<li><p><code>r#"\".*\""</code>: This pattern matches string literals. The <code>.*</code> matches any character (except for line terminators) any number of times, and <code>\"</code> matches quotation marks.</p>
</li>
</ul>
</li>
<li><p><strong>Identifiers</strong></p>
<ul>
<li><code>r"[a-zA-Z_][a-zA-Z0-9_]* ="</code>: This matches identifiers. Identifiers start with a letter or underscore, followed by any number of letters, digits, or underscores. The space and <code>=</code> at the end ensure we're matching an assignment operation.</li>
</ul>
</li>
<li><p><strong>Operators and Punctuation</strong></p>
<ul>
<li><code>r"\+"</code>, <code>r"="</code>, <code>r";"</code>, <code>r"\("</code>, <code>r"\)"</code>, <code>r"\{"</code>, <code>r"}"</code>, <code>r"&gt;"</code>, <code>r"&lt;"</code>: These patterns match operators and punctuation characters. In regex, some characters like <code>+</code>, <code>(</code>, <code>)</code>, <code>{</code>, <code>}</code> are special characters. To match them literally, they are escaped with a backslash <code>\</code>.</li>
</ul>
</li>
</ol>
<p>Boy was that a lot of information to consume!! But we're past the hard stuff now, or not given how much you like rust lol. But let's bring it all together and write the logic for our lexer in <code>lexer.rs</code>.</p>
<h3 id="heading-writing-lexerrs">Writing lexer.rs</h3>
<p>Now that we have implemented the tools to discover the tokens it's time to use them and find the token. But how do we even use them to identify the token? The brute forced way is to:</p>
<ol>
<li><p>Find the first regex match for each token regex.</p>
</li>
<li><p>Find the matches that have the smallest starting index.</p>
<ul>
<li>If many matches have the same smallest starting index then choose the match that is largest in length or has the maximum <code>ending_index-starting_index</code>.</li>
</ul>
</li>
<li><p>Remove the lexeme of the token that we selected from the program via regex.</p>
</li>
<li><p>Repeat the Process.</p>
</li>
</ol>
<p>This is good but there is too much redundancy in nested looping going on here!! I think instead what we can do is get all the regex matches at once and process them together, this way has many issues but is perfect for the program we want to compile. Here is the process:</p>
<ol>
<li><p>Iterate over an array of token string <code>tokens</code> in the descending order of their priority. That means indices of keyword token_strings would be lower than others. Aside from this initialize a <code>current_input</code> that holds the same value as the program and <code>match_vec</code> that's a vector of tuples with elements <code>(lexeme, starting_index, ending_index)</code>.</p>
<pre><code class="lang-rust">     <span class="hljs-keyword">let</span> current_input = program;
     <span class="hljs-keyword">let</span> tokens = [
         <span class="hljs-string">"Print"</span>, <span class="hljs-comment">// Highest Priority</span>
         <span class="hljs-string">"If"</span>,
         <span class="hljs-string">"Else"</span>,
         <span class="hljs-string">"Int"</span>,
         <span class="hljs-string">"Plus"</span>,
         <span class="hljs-string">"Assign"</span>,
         <span class="hljs-string">"Semicolon"</span>,
         <span class="hljs-string">"LeftParen"</span>,
         <span class="hljs-string">"RightParen"</span>,
         <span class="hljs-string">"LeftBrace"</span>,
         <span class="hljs-string">"RightBrace"</span>,
         <span class="hljs-string">"GreaterThan"</span>,
         <span class="hljs-string">"LessThan"</span>,
         <span class="hljs-string">"IntegerLiteral"</span>,
         <span class="hljs-string">"StringLiteral"</span>,
         <span class="hljs-string">"Identifier"</span>, <span class="hljs-comment">// Lowest Priority</span>
     ];
     <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> match_vec: <span class="hljs-built_in">Vec</span>&lt;(&amp;<span class="hljs-built_in">str</span>, <span class="hljs-built_in">usize</span>, <span class="hljs-built_in">usize</span>)&gt; = <span class="hljs-built_in">Vec</span>::new();
</code></pre>
</li>
<li><p>Start iteration over each <code>token</code> in <code>tokens</code> array:</p>
<pre><code class="lang-rust">     <span class="hljs-keyword">for</span> token <span class="hljs-keyword">in</span> tokens.iter() {
</code></pre>
</li>
<li><p>Get the regex pattern string <code>token_regex</code> for the <code>token</code> token string using the <code>get_regex</code> method implemented under <code>Token</code> and initialize the <code>Regex</code> object <code>re</code> for the regex pattern we got.</p>
<pre><code class="lang-rust">         <span class="hljs-keyword">let</span> token_regex = Token::get_token_regex(token);
         <span class="hljs-keyword">let</span> re = Regex::new(token_regex.as_str()).unwrap();
</code></pre>
</li>
<li><p>Use <code>re</code> to find all matches in <code>current_input</code>. This is done using the <code>find_iter</code> method, which returns an iterator over all non-overlapping matches of the pattern in the string. Each match found is a range indicating the match's starting index and ending index in the input string.</p>
<pre><code class="lang-rust">         <span class="hljs-keyword">let</span> matched = re.find_iter(current_input);
</code></pre>
</li>
<li><p>For each match found, create a tuple consisting of the token string, the starting index, and the ending index of the match in <code>current_input</code>. Append each of these tuples to <code>match_vec</code>. This step gathers all the matches for all token types in the input program. If there are no matches found for a token string skip the further steps in loop.</p>
<pre><code class="lang-rust">         <span class="hljs-keyword">let</span> all_matches = matched.collect::&lt;<span class="hljs-built_in">Vec</span>&lt;_&gt;&gt;();

         <span class="hljs-keyword">if</span> all_matches.len() == <span class="hljs-number">0</span> {
             <span class="hljs-keyword">continue</span>;
         }

         <span class="hljs-keyword">for</span> m <span class="hljs-keyword">in</span> all_matches.iter() {
             match_vec.push((token, m.start(), m.end()));
         }
     }
</code></pre>
</li>
<li><p>Once all matches for all tokens have been found and stored in <code>match_vec</code>, sort this vector. The sorting should primarily be by the starting index of the match (to process the input program from start to end) and secondarily by the length of the match (to prefer longer matches over shorter ones when they start at the same position). This respects both the priority of tokens and the rule of maximal munch (longest match).</p>
<pre><code class="lang-rust">     match_vec.sort_by(|a, b| a.<span class="hljs-number">1</span>.cmp(&amp;b.<span class="hljs-number">1</span>).then_with(|| (b.<span class="hljs-number">2</span> - b.<span class="hljs-number">1</span>).cmp(&amp;(a.<span class="hljs-number">2</span> - a.<span class="hljs-number">1</span>))));
</code></pre>
</li>
<li><p>Iterate over the sorted <code>match_vec</code>, and for each tuple, create a <code>Token</code> instance corresponding to the token type with the lexeme extracted from <code>current_input</code> using the starting and ending indices using the <code>get_token</code> method.</p>
<pre><code class="lang-rust">     <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> token_vec: <span class="hljs-built_in">Vec</span>&lt;Token&gt; = <span class="hljs-built_in">Vec</span>::new();
     <span class="hljs-keyword">for</span> m <span class="hljs-keyword">in</span> match_vec.iter() {
         token_vec.push(Token::get_token(m.<span class="hljs-number">0</span>, <span class="hljs-literal">Some</span>(&amp;current_input[m.<span class="hljs-number">1</span>..m.<span class="hljs-number">2</span>])));
     }
</code></pre>
</li>
<li><p>Return the token vector.</p>
<pre><code class="lang-rust">     token_vec
 }
</code></pre>
</li>
</ol>
<p>And that's it!! You have just created your own memory-safe lexer in Rust in the most non-idiomatic Rust way possible. Well if you go by the idiomatic rust route you'll be stuck in syntax loops, but hey this way everyone understands it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706802941204/12c358e6-2e08-4430-aa8f-138a162816e2.jpeg" alt class="image--center mx-auto" /></p>
<p>Now that we have the lexer it's time to test it!</p>
<h3 id="heading-testing-our-lexer">Testing our Lexer</h3>
<p>In order to test our lexer we'll be writing the test code in <code>main.rs</code> we just need to define the code we need to compile as a string and get the results from the <code>lex_program</code> method we wrote above. That's all!!</p>
<pre><code class="lang-rust"><span class="hljs-keyword">mod</span> lexing;

<span class="hljs-keyword">use</span> lexing::lexer::lex_program;

<span class="hljs-keyword">const</span> PROGRAM: &amp;<span class="hljs-built_in">str</span> = <span class="hljs-string">"
int x = 5;
int y = 6;
int z = x + y;

if (z &gt; 10) {
    print(\"Hello, world!\");
} else {
    print(\"Goodbye, world!\");
}
"</span>;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> tokens = lex_program(PROGRAM);

    <span class="hljs-keyword">for</span> token <span class="hljs-keyword">in</span> tokens.iter() {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, token);
    }
}
</code></pre>
<p>Everything is pretty standard except that <code>mod lexing;</code> part. Let me explain. This line declares a module named <code>lexing</code>. Rust will look for the definition of this module in a file named <code>lexing.rs</code> or in a file named <code>mod.rs</code> inside the <strong>lexing</strong> directory. We defined the <code>mod.rs</code> file, through which it'll bring the <code>lex_program</code> into <code>main.rs</code> file's namespace.</p>
<p>And that's it!! Take this moment and clap for yourself, cuz you've just built your first lexer. LET'S GOOOOO!!!!</p>
<p><img src="https://media.makeameme.org/created/time-to-chill-f24b05814f.jpg" alt="time to chill - Pampered Cat Meme Meme Generator" class="image--center mx-auto" /></p>
<p>The next thing you can do is you can understand the theory behind regular how regex is implemented. But well it's up to you because that's more of a conventional college curriculum stuff.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">For the sake of curiosity, Regex is implemented using something called <strong>Finite Automata(FA) </strong>under which there are two types: <strong>Non-Deterministic FA(NFA)</strong> and <strong>Deterministic FA(DFA)</strong>. Both NFA and DFA can be used to implement regex and each operation in regex is a sub automata in automata that is finally created. NFAs are more compact but slower than DFAs, while DFAs are faster and much larger than NFAs. Both are good for the task but we can implement the regex based on the tradeoff we feel suitable for the language we are building.</div>
</div>

<p>As for the next steps for the series, we'll be using the tokens we got from the lexer we coded and build a parse tree or Abstract Syntax Tree from it! Stay tuned for <strong>Writing a Compiler in Rust #2: Parsing.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706789935903/1d657ea1-f193-4034-947f-be9b87a66770.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-from-me-to-you">From Me to You</h2>
<p>In this blog, we covered how Lexers work and how we can code one in Rust. Well, Rust wasn't the smoothest part about what we did but hey there is a first time for everything and this was probably the first time you got angry that a programming language exists. Jokes aside compilers be a tricky topic to understand but coding one makes everything clear. Hope you learned something new!</p>
]]></content:encoded></item><item><title><![CDATA[Transformers: Attention is all you need]]></title><description><![CDATA[Let's go ahead and break down the sections of the paper, **Attention is all you need**. To give you a gist of what'll be there, it'll be an explanation of…]]></description><link>https://krypticmouse.hashnode.dev/attention-is-all-you-need</link><guid isPermaLink="true">https://krypticmouse.hashnode.dev/attention-is-all-you-need</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[nlp]]></category><category><![CDATA[Python]]></category><category><![CDATA[Artificial Intelligence]]></category><dc:creator><![CDATA[Herumb Shandilya]]></dc:creator><pubDate>Thu, 09 Dec 2021 22:53:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1638987431300/0yWP8XDYJ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Attention is Transformer’s breath,</p>
<p>Multi-Head is Transformer’s release,</p>
<p>RNNs thou wert and art,</p>
<p>May thy model reach to greater accuracy.</p>
<p>Látom.</p>
<p>- Enen No Shouboutai</p>
</blockquote>
<p>I'm getting tired of butchering anime and video game quotes so I'm thinking I should butcher some meme quotes next time. Anyways, well I have been writing on a lot of topics but something I always wanted to write about is probably explaining a research paper.</p>
<p>I mean I've been seeing blogs that go by the name of <strong>Paper Dissected</strong> so I wanted to try writing one myself. Well this is going to be my first try in this and frankly, I have no idea how it'll be but let's give it a try, shall we?</p>
<p>I guess it's safe to say that Attention Mechanism and Transformers is something that recently took over NLP. Not only did it show improvements over the SOTA models at the time but also overcome the shortcoming of the RNN models like LSTM and GRU.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631918244839/oF2h1CrF8.jpeg" alt="1610374526-cheems1 (2).jpg" /></p>
<p>So let's go ahead and break down the sections of the paper, <strong>Attention is all you need</strong>. To give you a gist of what'll be there, it'll be an explanation of each section in the paper like abstract, introduction, model architecture, etc.</p>
<h1 id="heading-abstract">Abstract</h1>
<p>This section pretty much summarizes the whole paper not in terms of working but rather in terms of what it has to offer. It starts with explaining how Seq2Seq models usually use RNN and CNN for encoder and decoder, and how the best ones connect encoder and decoder via attention mechanism.</p>
<p>Now just to be clear, attention itself is not a new concept but to rely completely on attention is something that this paper introduced. It went ahead explaining the results achieved on the machine translation task which were like the following on WMT-2014 dataset:-</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>MT - Task</td><td>BLEU Score</td></tr>
</thead>
<tbody>
<tr>
<td><strong>English to German</strong></td><td>28.4</td></tr>
<tr>
<td><strong>English to French</strong></td><td>41.8</td></tr>
</tbody>
</table>
</div><p>It also took 3.5 days and 8 GPUs to train on, which is certainly out of my budget. But the main thing that shined a bit differently than others in the abstract section was:-</p>
<blockquote>
<p>Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train.</p>
</blockquote>
<p>We saw how results were better than traditional models but the thing that separated transformers from LSTM is parallel computation. This can feel a bit tricky to understand at the start so let's break it down. By nature, RNN models aren't parallel but rather Sequential and this is because they compute results one step at a time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631732056936/0U5QBxJEa.png" alt="YjlBt.png" /></p>
<p>However, in the Transformer model, there is no such thing as "time steps" but rather the inputs are passed all together and all this is made possible due to multi-headed attention and other stuff which we'll talk about later.</p>
<h1 id="heading-introduction">Introduction</h1>
<p>This section mainly talks about the working of RNNs and it's limitations, along with the recent developments to tackle them. Now that we are at it let's understand how does Seq2Seq modeling working in the case of RNNs and to make it easier, take a look a look at the picture below:-</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631910532329/yoH-0RbHk.png" alt="Seq2Seq Blog Img #1.png" /></p>
<p>Seq2Seq Models consists of 2 models i.e. an Encoder and a Decoder. The Encoder model takes the text as input and generates a Context Vector as an output which is nothing but the last hidden state of RNN. Encoders and Decoders are nothing but RNNs and in few instances CNN 🌚.</p>
<p>Another thing you'll notice is the crosses above RNN cells except the last one that doesn't mean they aren't produced, they are but we just don't use them and all we'll be doing is to take the context vector from the last time step and feeding it to the decoder as input who'll output each word at a time giving us the resultant text.</p>
<p>In attention, however, you'll be taking the outputs of all the time step of encoder so you don't discard in that case. I mean you can also do mean pooling on all the states and pass that as context vector, so attention isn't the only way that uses all the states. But how does the decoder predict the words? Let's see, I'll try to be brief.</p>
<p>In the decoder, the first token is the special token signifying the start of the sentence along with the context vector from the encoder, after that you pass the previous output as input to the decoder along with the hidden state to generate new output. However during training, we feed the ground-truth value of targets as input to the decoder, this is known as <strong>Teacher Forcing</strong>. Without which the model weights will be updated on inferred text making it difficult for model to learn from.</p>
<p>However during inference, you'll use generated output as input to generate the next token, and it's cool except the output is being constructed on the context of inferred output rather than actual ones, which causes discrepancy during training and inference, giving rise to the problem of <strong>exposure bias</strong>.</p>
<p>Back to the topic, the nature of RNNs is sequential which makes parallelization difficult for training, making RNN models take more time to train. However, there are few developments that tackle it:-</p>
<blockquote>
<p>Recent work has achieved significant improvements in computational efficiency through <strong>factorization tricks</strong> and <strong>conditional computation</strong>, while also improving model performance in the case of the latter. The fundamental constraint of sequential computation, however, remains.</p>
</blockquote>
<p>To understand the factorization trick you can go ahead and read another paper, i.e. <strong>Factorization Tricks for LSTM Networks</strong> by Oleksii and Boris, which I recommend but I'll give you the gist of it.</p>
<blockquote>
<p>The major part of LSTMP cell computation is in computing affine transform T because it involves multiplication with 4n × 2p matrix W.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631916140101/s9rWIKqZA.png" alt="image.png" /></p>
<p>The aim of the factorization trick is to approximate that W by replacing it with the product of 2 matrices W1(2p*r) and W2(r*4n), this way takes fewer parameters (2p<em>r + r</em>4n) as compared to W (2p*4n) given r &lt; p &lt;=n. Another factorization trick proposes to think parts of inputs and the hidden states as independent of each other and calculate affine transforms of these groups individually and parallelly.</p>
<p>I know it's a lot to grasp so if you don't understand it all at the moment it's fine, important thing to understand is that <strong>many attempts have been made to improve RNNs but the sequential nature isn't completely removed</strong>. The attention model did help in capturing long-term dependencies and improve results, however, it was used along with RNNs.</p>
<p>There is another concept of conditional computation that aims at activating parts of the network to improve computational efficiency, and performance too in this case, but let's not dive much into it. But if you want to you can read this <a target="_blank" href="https://trace.tennessee.edu/cgi/viewcontent.cgi?article=5323&amp;context=utk_graddiss"><strong>short book</strong></a> on the same.</p>
<p>The transformer model on the other hand relies entirely on attention mechanism allowing it to be more parallelizable and give better results with the cost of training being 12 hours on 8 P100 GPUs, something that even Colab Pro users can't get their hands on all the time anymore 🥲.</p>
<h1 id="heading-model-architecture">Model Architecture</h1>
<p>Finally, we've come to the real deal. Now while I wanna try and break down the explanation sub-section wise, I know that may or may not end up leaving you kinda confused, and hence instead of explaining each sub-section of this section we'll dismantle the architecture step by step and understand how it works.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632343488045/17Un25edDk.png" alt="image.png" /></p>
<h2 id="heading-input-embeddings">Input Embeddings</h2>
<p>Let's start from the beginning, what you have with you is a sentence or bunch of sentences. Now you can't exactly feed it to the model as it is so you need a way to convert it to a form more suitable for it. When we used RNNs for text classification or seq2seq we convert our text to <strong>word embeddings</strong>.</p>
<p>These embeddings are nothing but vector representations of words such that words with similar meanings are closer to each other. But what does closer mean? Mathematically, closer means the similarity score is high. This score can be anything but cosine similarity is popular so feel free to think that. Once we have our embeddings to use we are all set! Are we?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632351034260/Qo6JVLncJ.jpeg" alt="4824982 (1).jpg" /></p>
<p>Technically, yes we are since these embeddings can be used with RNNs and CNNs because they are able to capture the ordering into consideration. But Transformers use only self-attention, which takes all the words at the same time hence it is not able to take the order of words into consideration. To fix this problem we introduce something called <strong>positional encodings</strong>.</p>
<h2 id="heading-positional-encodings">Positional Encodings</h2>
<p>So as mentioned before, inherently attention model is not able to take the order of words into consideration. In order to compensate for this, we use something called Positional Encodings. Don't be intimidated by the name it's actually much more simple. Let's dive a bit deeper into this.</p>
<h3 id="heading-need-of-positional-encodings">Need of Positional Encodings</h3>
<p>When working with text it's really important to take words order into consideration. Why? The order of words defines the structure of the sentence and this structure helps in providing the context.</p>
<p>RNNs by nature are sequential in nature by taking inputs one by one and updating hidden states accordingly, but the same is not the case with attention since it takes the words all at once. Why this is so, is something we'll understand in the next section but for now, let's say that's how it is.</p>
<p>So we need some extra sources of information in our embeddings to convey this information, something that could tell the position of a word in a sentence. To do so we can add an extra embedding or matrix to our word embeddings to provide info regarding the ordering of the word. But how?</p>
<h3 id="heading-finding-positional-encodings">Finding Positional Encodings</h3>
<p>Well in the most simple case you can use a one-hot encoded form of [0,1,2,3,4,5,..., pos] as positional encodings. You can train an embedding layer to find the <strong>positional embedding</strong> matrix, where each row has the positional embedding for word at pos index, for this and add it to input embeddings.</p>
<p>In the paper, however, the proposed approach uses a combination of sin and cos function to find the encodings. Take a look at the following picture:-</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632693800233/lcT9IBipy.png" alt="i (3).png" /></p>
<p>As you can see in the above picture the encodings are found by using a combination of sin and cos function. The function is quite self-explanatory, it says that for the embedding of a word at position <strong>pos</strong>:-</p>
<ul>
<li><p>The value at index <strong>2i</strong> is given using the <strong>sin</strong> function, colored red.</p>
</li>
<li><p>The value at index <strong>2i +1</strong> is given using the <strong>cos</strong> function, colored blue.</p>
</li>
</ul>
<p>But why are we using this particular function? Well let's hear from the authors themselves:-</p>
<blockquote>
<p>We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions since, for any fixed offset k, PEpos+k can be represented as a linear function of PEpos.</p>
</blockquote>
<p>Well, researchers sure love to make stuff seem more complicated, don't they? It's fine if you don't understand the above sentence, take it as a confirmation that you're still sane.</p>
<p>What the sentence means to say is that given the positional encoding of the word at <strong>pos</strong> you can find the positional encoding of word at <strong>pos + k</strong> by applying some linear transformation on the positional encoding of <strong>pos</strong>. Mathematically, it can be written like this:-</p>
<p>\[PE_{p+k} = T * PE_p\]</p><p>Writing <strong>pos</strong> as <strong>p</strong> in the above equation since latex is getting messed up for some reason. The important thing to know is that the matrix T can be used to find PE at pos+k but what is this T? Can we find it? Well yes, that T is a rotational matrix that depends on offset k rather than pos. Wait what! How?</p>
<p>Well, you can derive it, and here is a really good <a target="_blank" href="https://kazemnejad.com/blog/transformer_architecture_positional_encoding/">blog by Amirhossein</a> doing the same. There is another <a target="_blank" href="https://timodenk.com/blog/linear-relationships-in-the-transformers-positional-encoding/">blog by Timo Denk</a> that proves the linear relationship between PE at pos and pos+k but the first one explains in a much simpler fashion, but do give both a read.</p>
<h3 id="heading-improving-a-bit-more">Improving a bit more</h3>
<p>Wow so everything is dope, right? Fortunately or unfortunately, No. Even though everything might seem super nice with these encodings, which it is, what these really are doing is finding values for given pos and i values, these are also called <strong>Absolute Positional Encodings</strong>. While the altering of sin and cosine might be able to add relative nature, we might actually have something better i.e. <strong>Relative Positional Encodings</strong>.</p>
<p>Following this paper, there was another paper released i.e. <strong>Self-Attention with Relative Position Representations</strong> by <a target="_blank" href="https://arxiv.org/pdf/1803.02155.pdf">Shaw et. al. 2019</a>. This paper introduces a modified attention mechanism which is mostly the same except this one has 2 matrices that are added to Key and Value Vector and the aim is that they'll be able to induce pairwise relationships in the inputs. In the author's own words:-</p>
<blockquote>
<p>We propose an extension to self-attention to consider the pairwise relationships between input elements. In this sense, we model the input as a labeled, directed, fully connected graph.</p>
</blockquote>
<p>The paper is actually a pretty decent read and you should give it a try. Since this paper doesn't use these embeddings we'll not go into the detail of these. There are many papers that try to come up with better Positional Encodings and try to improve them, but what they are used for and proper intuition is something you should aim to understand.</p>
<h2 id="heading-attention">Attention</h2>
<p>Attention is something that we've been talking about a lot in this blog, after all that's what this paper is about. But what does it actually mean? So before diving into the proposed method for attention calculation in this paper, we'll go ahead and understand what attention is and how it helps our cause.</p>
<p>So when we do Seq2Seq with RNNs we have an encoder and decoder network in which the work of the decoder is to generate a sentence given <strong>context vector</strong>. This context vector is nothing but the last hidden state of the encoder which is RNN based model. So what's the issue? Well, you see:-</p>
<ul>
<li><p>The <strong>context vector</strong> is a vector of fixed length defined by hidden_dims but the sentences are of variable length and so what we are doing is squeezing info into a vector due to which information might be lost.</p>
</li>
<li><p>Another problem is that the generated sentences are based on the context of the whole sentence, however in doing so we might lose out on the local context of parts of the sentence that might've been helpful in tasks like translation.</p>
</li>
</ul>
<p>So in order to improve on this, we introduce <strong>attention</strong> and instead of working on the global context of the sentence by taking all the hidden states in the encoder and passes it to the decoder. The decoder, in this case, doesn't produce the output directly instead it'll calculate the attention score for the states and creates the context vector for that particular time step given the attention score, the encoder hidden states, and the input vector, output of prev. step or last input token.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633217192689/yLRmt7ySf.png" alt="Normal Decoder.png" /></p>
<p>But how does this help? Well, what attention does is that it generates a context vector at each time step of the decoder based on attention score and this attention score helps to amplify the more important words to focus on during that time step in order to improve the quality of results. If you calculate attention among the words of the input sequence it's called <strong>Self Attention</strong> and when you calculate attention among the words of the input and output sequence it's called <strong>General Attention</strong>.</p>
<p>Now based on the architecture you have 2 types of attention-based Seq2Seq models i.e. <strong>Bahdanau Attention</strong> and <strong>Luong Attention</strong>. Except the architecture and computation both are basically the same but if you wanna learn more you can go ahead and read the paper, <strong>Effective Approaches to Attention-based Neural Machine Translation</strong> by <a target="_blank" href="https://arxiv.org/abs/1508.04025">Luong et. al. 2015</a>.</p>
<h3 id="heading-scaled-dot-product-attention">Scaled Dot-Product Attention</h3>
<p>We have a basic idea of how attention works in RNN now, but we don't exactly have an RNN in Transformer or a way to sequentially input data. So the proposed method for calculating attention is via something called <strong>Scaled Dot-Product Attention</strong>, which is basically a bunch of matrix multiplication operations.</p>
<p>But before diving in, let's talk about QKV or Query-Key-Value vectors and their dimensions. Throughout the model, the dimension of columns of the resultant matrix from each layer is set to <strong>512</strong> which is denoted by \( d_{model} \) .</p>
<p>So if we have <strong>m</strong> rows in word embedding we'll have the resultant matrix of dimension \( m * d_{model} \) , this column dimension is consistent for all the layers in the model including the embedding layer.</p>
<p>This is done to facilitate the residual connections, which we'll talk about later. Now that we have output dims cleared let's talk about columns of QKV vectors.</p>
<p>For now, just remember the dimension of QKV vectors being 64, the reasoning is something we'll discuss in Multiheaded attention. The dimensions of Query and Key vector are the same and are denoted by \( d_k \) , and even though here it is same the dimensions of value vector can be different and is denoted by \( d_v \) . So to sum it all up we'll have the following notation for dimensions:-</p>
<p>$$d_{model} = 512$$</p><p>$$d_q = d_k = 64$$</p><p>$$d_v = 64$$</p><p>Now that we have the important stuff cleared, let's take a look at the following image that sums up the process of calculating attention:-</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632788371388/1NFBKy8H8D.png" alt="S C A L E.png" /></p>
<p>It might seem confusing so let's go in step by step on how attention is being calculated and how its equation is constructed:-</p>
<ul>
<li><p>You start by finding <em>Query</em>, <em>Key</em>, and <em>Value</em> vector by multiplying the input matrix with their corresponding weight vector. The dims of these vectors are something we'll discuss in Multi Headed Attention Section. For now, let's just focus on understanding the equation.</p>
<p>  \(Attention(Q,K,V)\)</p>
</li>
<li><p>Apply Matrix Multiplication on <em>Query</em> and <em>Key</em> Vector.</p>
<p>  \(Attention(Q,K,V)=QKT\)</p>
</li>
<li><p>Scale the result of above with \( \sqrt{d_k} \) . It was observed that for small values of \( d_k \) additive attention and dot product attention perform similarly. But for larger values of \( d_k \) additive attention outperforms dot product attention without scaling. As mentioned in paper, that for large value the result may explode and may push softmax to smaller gradients. To counteract this \( \frac{1}{\sqrt{d_k}} \) was used for scaling. As to why this occurs, paper mentions:-</p>
</li>
</ul>
<blockquote>
<p>To illustrate why the dot products get large, assume that the components of q and k are independent random variables with mean 0 and variance 1. Then their dot product has mean 0 and variance d_k.</p>
</blockquote>
<ul>
<li><p>Applying softmax on the result of the above.</p>
<p>  \(Attention(Q,K,V)=softmax((QK^T)/\sqrt{d_k})\)</p>
</li>
<li><p>Apply Matrix Multiplication on result and <em>Value</em> Vector and get the final result.</p>
<p>  \(Attention(Q,K,V)=softmax((QK^T)/\sqrt{dk})V\)</p>
</li>
</ul>
<p>There you go that's how you find attention using Scaled Dot Product Attention. Just for the info, this is not the absolute way to find attention, there are other ways to calculate attention like additive attention, dot-product(unscaled) attention. While the two are similar in complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.</p>
<p>Now let's take a look at the newly proposed approach where instead of calculating attention one time we calculate it multiple times and then concatenate the results. Yep, it is indeed <strong>Multi-Headed Attention</strong>.</p>
<h3 id="heading-multi-headed-attention">Multi-Headed Attention</h3>
<p>Let's talk about the beast that the paper proposed and when I say "beast" I mean it. The paper suggested that instead of calculating attention one time we can calculate it <strong>h</strong> times with \(d_q\), \(d_k\), \(d_v\) dimensioned QKV vectors found after passing each of them from a Linear Layer.</p>
<p>We then use them to calculate attention values from each attention head depicted by head_i and concatenate these heads forming \( d_{model} \) dimensional resultant vector. After that, we'll pass them through another linear layer to get our Multi-Headed Attention output. Architecture wise it looks like this:-</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638644522204/RBUNc_MHH.png" alt="Linear.png" /></p>
<p>One thing to note is that the value of d_q, d_v, and d_k will be <strong>d_model / h</strong>, that's why after you concatenate, the attention head's output it becomes d_model sized vector. In this paper, the value of <strong>h</strong> for the optimal model was 8. So d_k, d_v, and d_q become 512/8 = 64.</p>
<h4 id="heading-why-does-it-work">Why does it Work?</h4>
<p>But after hearing all this it's only sensible to ask. Why does this even work? To answer this query, we should go and take a look at the paper <strong>"Analyzing Multi-Head Self-Attention"</strong> by <a target="_blank" href="https://arxiv.org/pdf/1905.09418.pdf">Voita et. al. 2019</a>. Where they basically try to find the roles that different attention heads played along with other stuff which we'll talk about later i.e. Attention Head Pruning.</p>
<p>To explain the gist of it the conclusion was, that based on roles attention heads can be divided into 3 parts:-</p>
<ul>
<li><p><strong>Positional Heads:</strong> Heads where the maximum attention weights was assigned to a specific relative position. This was usually +/- 1 in practice signifying attention to adjacent positions</p>
</li>
<li><p>**Syntactical Heads: ** Head attends to tokens corresponding to any of the major syntactic relations in a sentence. In the paper, they analyze direct relations like nominal subject, direct object, adjectival modifier, and adverbial modifier.</p>
</li>
<li><p><strong>Rare Word Heads</strong>: Heads attend to the least frequent tokens in a sentence.</p>
</li>
</ul>
<p>So different heads try to perform different task cool, but do we need all of them? We have only 3 types right? Does that mean other heads are useless? Yes and No. Let's understand the <strong>Yes</strong> part first.</p>
<p>Yes, attention heads are important and in fact, that's exactly what the blog <strong>"Are Sixteen Heads Really Better than One?"</strong> by <a target="_blank" href="https://blog.ml.cmu.edu/2020/03/20/are-sixteen-heads-really-better-than-one/">Paul Michael</a> tries to find. In the blog, he tried to explain how the performance was affected when attention heads were pruned. After the experiment they found the following result:-</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638650058322/s9kG6ry4m.png" alt="image.png" /></p>
<p>As you can see the BLEU Score is really affected after pruning the heads however like other metrics the dip is observed after more than 60% heads are pruned. This leads us to the <strong>No</strong> part. I mean kinda No.</p>
<p>Even though we just saw that heads are important we can also prune one or a few of them without seeing a major dip in the performance, something that both the mentioned sources, that I highly recommend you to go through, suggested. Phew that was a lot, now that we have the initial stuff cleared up, let's get back to the architecture. I promise this point forward is a smooth sailing simple life, probably xD.</p>
<h2 id="heading-encoder">Encoder</h2>
<p>If we try to understand the architecture of Encoder it can be broken into 2 parts:-</p>
<ul>
<li><p>Attention Layer</p>
</li>
<li><p>Feed Forward Layer</p>
</li>
</ul>
<p>Yes that's it, you are already familiar with Attention Layer which is nothing but Multi Headed Attention with 8 heads and the Feed Forward Layer is a basic Neural Network with a single hidden layer with 2048 nodes and 512 nodes in input and output layer. Visually it'll look something like this:-</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638657930173/RL6ONG63c.png" alt="Multi-Headed Attention.png" /></p>
<p>Its flow of Infomation is really simple, or not depending on your knowledge of skip connections. If I have to explain in one line skip connection is basically <strong>adding input to the output</strong>.</p>
<p>I know it sounds weird, but trust me it makes sense. ResNet model was the one that popularised these skip connections which provides an alternate path for gradients to flow. They helped train deeper models without running into vanishing gradient problem. So if x is the input to a block and f(x) is the output of the block then skip connections basically add them both making <strong>x + f(x)</strong> the new output.</p>
<p>$$f'(x) = x + f(x)$$</p><p>Now that we are all on the same page, let's step by step go through the flow of info in an encoder block:-</p>
<ol>
<li><p>Encoder block receives an input <strong>X</strong>.</p>
</li>
<li><p>X is supplied to Multi-Headed Attention Layer. QKV all will be the same i.e. <strong>X</strong>.</p>
</li>
<li><p>Multi Headed Attention does the magic and generates an output M(x).</p>
</li>
<li><p>Add X to M(x) because of skip connection.</p>
</li>
<li><p>Apply Layer Normalisation to X + M(x), let's call this N(x).</p>
</li>
<li><p>Pass N(x) to Feed Forward layer to generate an output F(x).</p>
</li>
<li><p>Add N(x) in F(x) because of skip connection again.</p>
</li>
<li><p>Apply Layer Normalisation to F(x) + N(x), let's call this E(x) which is the output of this encoder block.</p>
</li>
</ol>
<p>One last thing, the above is flow of info for one encoder block. This encoder block's output will be passed on to the next encoder block and the architecture of all encoder blocks is the same. The paper proposed the architecture with <strong>6 encoder blocks</strong>. I swear I need to learn animation one of these days, would make stuff much much easier.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638659972564/YTnCToXMN.png" alt="image.png" /></p>
<p>Yea I know too much info xD, but hey that's all that you need to know about Encoders. The output of the last encoder block is passed to the decoder as KV vector values, which is our next topic of discussion. We are almost near the end, so hang in there 😬.</p>
<h2 id="heading-decoder">Decoder</h2>
<p>Finally, we are at the last step of the architecture, to be honest decoder is not really that different from than encoder except the fact that here were have an extra layer for masked multi-headed attention. We'll get into the details of that in a bit, but let's get an overview of how a decoder block looks:-</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638738474914/aVah0DKWI.png" alt="Decoder (1).png" /></p>
<p>Before going into the flow of information let's understand exactly what is the input and output of the decoder block. As far as input is concerned the decoder takes 2 inputs:-</p>
<ol>
<li><p><strong>Encoder Output:</strong> This is will be fed as KV Vectors for multi-headed attention in the 2nd layer, this is usually referred to as Encoder-Decoder Attention. All <strong>6 Decoder Blocks</strong> will take the encoder output from the last block as input for encoder-decoder attention.</p>
</li>
<li><p><strong>Output Embedding:</strong> These are the embeddings of the target sentence. But wait!? We don't have a target in testing! So what are we inputting here then? Let's see.</p>
</li>
</ol>
<p>Well usually the first input to the decoder is a special token signifying the start of the output sentence and the output is the token that comes after this. This output is the output of time step 1.</p>
<p>After that, the input to decoder becomes the tokens until a certain timestep i.e. for the 5th timestep input will be all generated tokens till the 4th timestep. After that, it'll keep on giving an output until it throws a special token signifying the end of the output sentence.</p>
<p>Let's understand the flow of information in decoder block to get a better understanding:-</p>
<ol>
<li><p>Decoder block receives an input <strong>X</strong>.</p>
</li>
<li><p>X is supplied to Masked Multi-Headed Attention as QKV vector, to get an output M(x).</p>
</li>
<li><p>Add X in M(x) because of skip connection.</p>
</li>
<li><p>Apply Layer Normalisation to X + M(x), let's call this N(x).</p>
</li>
<li><p>N(x) is supplied to Multi-Headed Attention as Query and Encoder Output will be supplied as Key-Value..</p>
</li>
<li><p>Multi Headed Attention does the magic and generates an output O(x).</p>
</li>
<li><p>Add N(x) in O(x) because of skip connection.</p>
</li>
<li><p>Apply Layer Normalisation to N(x) + O(x), let's call this P(x).</p>
</li>
<li><p>Pass P(x) to Feed Forward layer to generate an output F(x).</p>
</li>
<li><p>Add P(x) in F(x) because of skip connection again.</p>
</li>
<li><p>Apply Layer Normalisation to P(x) + F(x), let's call this D(x) which is the output of this decoder block.</p>
</li>
</ol>
<p>But all that is nice but how does the decoder predict the next token? Actually, the output of the last decoder block is fed to a Linear Layer that gives an output vector of the size same as that of vocabulary. So depending on how many words the model knows that will be the size of the output vector of this Linear Layer.</p>
<p>Now once you have this vector you apply softmax on this to convert and interpret the values of this vector as probabilities. The token at the index of maximum probability is the output of that "time-step". Take a look at the following infographic to understand it better.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638817538390/vAicWO0-Q.png" alt="1.01.png" /></p>
<p>Well, that's basically how the decoder works, but we are still missing one key piece in the puzzle i.e. Masked Multi-Headed Attention. It's actually pretty simple and trust me it won't take much long to understand.</p>
<h3 id="heading-masked-multi-headed-attention">Masked Multi-Headed Attention</h3>
<p>If I have to say the difference between Normal Multi-Head Attention and Masked Multi-Head Attention it'll be that in Masked Multi-Head Attention we mask the output of attention score after a point for each token by replacing it with <strong>-inf</strong> and when it applies softmax these -inf become 0.</p>
<p>Well, that's fine but what exactly is going on? Let's understand. The reason we need such a thing in the first place is so that we can speed up training by being able to compute the probabilities of output token for each input token parallelly. The only reason we are doing this stuff is to speed up training.</p>
<p>And just to be clear this passing all at once stuff is something we'll do only in training, during inference we'll still do it step by step by passing previous outputs to get the new ones.</p>
<p>The aim of an autoregressive model is to find the next step given the previous ones but for parallelization, we'll be passing all the stuff together at once hence we'll need to hide the output of the attention score for the future time steps of that token to properly train the model. Let's understand this step by step to get a better understanding.</p>
<h4 id="heading-step-by-step-guide-to-masked-mha">Step-By-Step Guide to Masked MHA</h4>
<p>So let's start by knowing what exactly we need to find:-</p>
<p>$$P(x_{i+1}|[x_0, x_1, ..., x_i])$$</p><p>What the above equation means is that we'll need to find the <strong>probability of the next word given the previous ones in sequence</strong>. Now let's consider the following sentence and let's assume it to be the expected output:-</p>
<p>$$The \space cake \space was \space sour$$</p><p>If you pass words one by one you prevent seeing the future steps but for efficiency, you'll need to pass all the words together. When you do this you expose the decoder to future info, in order to prevent that we mask the weights of all j(&gt;i) future steps, i being the current time step.</p>
<p>So for the word <strong>cake</strong> in the above sentence, we'll mask the weight for words <strong>was</strong> and <strong>sour</strong>, the same way for the word <strong>was</strong> in the above sentence we'll mask the weight for <strong>sour</strong>. We can do this by adding a mask matrix to this:-</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638824585791/vkXCmdGyw.png" alt="Attention Matrix.png" /></p>
<p>Implementation-wise, you apply the mask after doing the scaled matrix multiplication of the QV vector in scaled dot product attention. After this you proceed normally, the only difference is this masking step.</p>
<h1 id="heading-training-and-results">Training and Results</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638824797235/s42ytjQf4.png" alt="image.png" /></p>
<p>Done! We are done with the architecture. We are officially out of the deadly stuff and now it's just simple stuff. So let's wrap it up. Let's start by going through some details regarding the training:-</p>
<ul>
<li><p><strong>Data:</strong> The WMT English German Dataset contained 4.7 million sentence pairs, with a vocabulary of about 37k tokens. The WMT English French Dataset contained 36 million sentence pairs, which is so big that my hard drive will die before loading it.</p>
</li>
<li><p><strong>Hardware:</strong> Richie Rich people xD. Trained on 8 Nvidia P100 GPU something which make me go bankrupt 100 times. Trained for 100k steps for 12hrs. The bigger variants were trained for 300k steps for 3.5 days.</p>
</li>
<li><p><strong>Optimizer:</strong> They used Adam optimizer with β1 = 0.9, β2 = 0.98 and epsilon = 10^−9. Increasing the learning rate linearly for the first warmup_steps training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. They used warmup_steps = 4000.</p>
</li>
<li><p>**Regularization: ** Dropout of 0.1 was applied to the sum of the positional and wor embeddings. Dropout was also applied to the output of the sublayer before the residual step. Label smoothing was also applied with epsilon = 0.1. Label Smoothing is a way to prevent the model from being too confident about it's prediction.</p>
</li>
</ul>
<p>That's all as far as training is concerned. Now the architecture I explained had very specific parameters but that's not the only model they tried. They actually tried a bunch of them and noted the result of each in the table below:-</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638742942369/YXSCN_Hzb.png" alt="image.png" /></p>
<p>As you can see big model performed the best out of all but between big model and base model with a small performance drop, I'll take my chance with the base one first.</p>
<p>That's all! We have finished the paper and reached the end, take a moment and clap for yourself.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638743290287/RzCFUzOdXI.gif" alt="PlayfulUnknownDuckbillcat-max-1mb.gif" /></p>
<h1 id="heading-from-me-to-you">From Me to You...</h1>
<p>Wow, that was a big blog and I won't lie it was tough to write. This is probably one of my longest and most experimental blog ever. I was super casual and explained everything as much as possible. At some point I wanted to just stop but every time I just thought, just a bit more.</p>
<p>Transformers are probably one of those revolutionary concepts in deep learning that changed the way we approached stuff and I hope I was able to dissect the paper that started it all. I hope you had fun reading it.</p>
<p>Forever and Always, Herumb.</p>
]]></content:encoded></item><item><title><![CDATA[PyTorch Lightning: DataModules, Callbacks, TPU, and Loggers]]></title><description><![CDATA[Leverage PyTorch with the help of PyTorch Lightning]]></description><link>https://krypticmouse.hashnode.dev/pytorch-lightning-datamodules-callbacks-tpu-and-loggers</link><guid isPermaLink="true">https://krypticmouse.hashnode.dev/pytorch-lightning-datamodules-callbacks-tpu-and-loggers</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[neural networks]]></category><category><![CDATA[Data Science]]></category><dc:creator><![CDATA[Herumb Shandilya]]></dc:creator><pubDate>Tue, 08 Jun 2021 16:41:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1623170330358/8kC_C7AgJ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>When I was a young man,</p>
<p>I had liberty but I didn’t see it, </p>
<p>I had time but I didn’t know it, </p>
<p>And I had PyTorch Lightning but I didn't use it.            </p>
<p>- Newbie PyTorch User</p>
</blockquote>
<p>Another Blog another great video game quote butchered by these hands. Anyways, when I was getting started with PyTorch one of the things that made me jealous was the fact that Tensorflow has so much support for monitoring the model performance. I mean I have to write a training loop with redundant steps while Tensorflow beginners were just passing and chilling.</p>
<p>So I did what most PyTorch newbies did, learned and wrote the training loop code until it became muscle memory and that is something you shouldn't do. Few tips for that is just understanding why each step works and once you do that every line of code starts to make sense, trust me once I did that I never forgot it again.</p>
<p>Back to the topic, one thing that I love about PyTorch is the extent to which I can customize it and how easy it is to debug. But still, it would be better if somehow I was able to keep those features and reduce the redundancy.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1623080889159/8CTEmcmR1.png" alt="Untitled design.png" /></p>
<p>Well there you have it, the solution is <strong>PyTorch Lightning</strong> I mean anyone with such a cool name is already destined for greatness but if that reason doesn't convince you then I hope that by the end of this article you will be. </p>
<p><strong>P.S.</strong> it's actually better if you have some basic idea about Lightning. If you wanna learn its basics try this article I wrote a while back on <a target="_blank" href="https://www.geeksforgeeks.org/training-neural-networks-using-pytorch-lightning/"><strong>Training Neural Networks using PyTorch Lighting</strong></a>.</p>
<h2 id="datasets-dataloaders-and-datamodule">Datasets, DataLoaders and DataModule</h2>
<p>There are two things that give me immense satisfaction in life, first is watching a newbie Vim user trying to exit Vim, and the second is watching a newbie PyTorch user trying to create Dataloader for custom data. So let's take a look at how you can create DataLoaders in PyTorch using an awesome utility called <strong>Dataset</strong>.</p>
<h3 id="the-dataset-class">The Dataset Class</h3>
<p>One of the things that is essential if you are learning PyTorch is how to create DataLoaders there are many ways to go for it I mean for Image you have <strong>ImageFolder</strong> utility in <strong>torchvision</strong> and for Text Data we have <strong>BucketIterator</strong> which I won't lie are quite handy but still what if the data you load isn't in the desired format? In that case, you can use the Dataset class, and not just that the thing that I love about Dataset class is that they are customizable to an extent you can't imagine. </p>
<p>In Dataset class you have 3 main functions that you must define, let's take a look at them:-</p>
<ul>
<li><p><strong><strong>init</strong>(self, *):</strong> The constructor function. there are infinite possibilities of things you can do here. Think of it as the <strong>staging area</strong> of our data. Usually, you pass either a path, a dataframe, or an array as the argument to this class's instance. Here you usually define class attributes like feature matrix and target vector. If you are working with an image you can assign transform variable, if you are working with the text you can assign a tokenizer variable etc. </p>
</li>
<li><p><strong><strong>len</strong>(self):</strong> The length function. this is where you'll return the length of the dataset, you basically return the length of the feature matrix or the dataset in whatever format you have.</p>
</li>
<li><p><strong><strong>getitem</strong>(self, idx):</strong> The fetching function. This is the function where you define how your data will be returned. You can apply various preprocessing to be applied on the data of at <strong>idx</strong> index here and then return its tensor along with other variables like mask or target by packing them in a list, tuple, dict, etc. I used to pack them in a list but when I saw <a target="_blank" href="https://www.youtube.com/watch?v=oWq6aVv5mC8&amp;ab_channel=AbhishekThakurAbhishekThakur"><strong>Abhishek Thakur's</strong></a> video on this I started using dicts and I never looked back since that day. </p>
</li>
</ul>
<p>The guy is a PyTorch madlad go watch his videos if you haven't already brilliant and to-the-point hands-on videos on many interesting topics. Let's keep all that aside for now and take an example, shall we? I'll be using <strong>make_classification</strong> to create the dataset to keep things simple.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> sklearn.datasets <span class="hljs-keyword">import</span> make_classification
<span class="hljs-keyword">from</span> torch.utils.data <span class="hljs-keyword">import</span> Dataset

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TabularData</span>(<span class="hljs-params">Dataset</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, X, Y, train = True</span>):</span>
        self.X = X
        self.Y = Y

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__len__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> len(self.X)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__getitem__</span>(<span class="hljs-params">self, idx</span>):</span>
        features = self.X[idx]

        <span class="hljs-keyword">if</span> self.Y <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
            target = self.Y[idx]
            <span class="hljs-keyword">return</span> {
                <span class="hljs-string">'X'</span> : torch.tensor(features, dtype = torch.float32),
                <span class="hljs-string">'Y'</span> : torch.tensor(target, dtype = torch.long)
            }

        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> {
                <span class="hljs-string">'X'</span> : torch.tensor(features, dtype = torch.float32)
            }

X, Y = make_classification()
train_data = TabularData(X, Y)
train_data[<span class="hljs-number">0</span>]
</code></pre>
<p>Output:-</p>
<pre><code class="lang-text">{'X': tensor([ 1.1018, -0.0042,  2.1382, -0.7926, -0.6016,  1.5499, -0.4010,  0.3327,
          0.1973, -1.3655,  0.4870,  0.7568, -0.7460, -0.8977,  0.1395,  0.0814,
         -1.4849, -0.2000,  1.2643,  0.4178]), 'Y': tensor(1)}
</code></pre>
<p>Subarashi! That seems to be working correctly you can try and experiment with what happens if you change the output of the classes a bit and check the results. But for this tutorial, we'll be working on Fashion MNIST data and thankfully in torchvision there already is a dataset for that so let's load that.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> torchvision <span class="hljs-keyword">import</span> datasets, transforms

transform = transforms.Compose([
    transforms.ToTensor()
])

train = datasets.FashionMNIST(<span class="hljs-string">''</span>,train = <span class="hljs-literal">True</span>, download = <span class="hljs-literal">True</span>, transform=transform)
test = datasets.FashionMNIST(<span class="hljs-string">''</span>,train = <span class="hljs-literal">False</span>, download = <span class="hljs-literal">True</span>, transform=transform)
</code></pre>
<p>Now that we have the data it's time to move onto DataLoaders.</p>
<h3 id="dataloaders">DataLoaders</h3>
<p>DataLoaders are responsible to take input a dataset and then pack the data in them into batches and create an iterator to iterate over these batches. They really make the whole batching process easier while keeps the customizability to the fullest. I mean you can define how to batch your data by writing your own <strong>collate_fn</strong>, what more do you want? </p>
<p>We saw how we can create a dataset class, to create its DataLoader you just pass that Dataset instance to the DataLoader and you are done. Let's see how to do it for the MNIST dataset that we created above and check it's output.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
<span class="hljs-keyword">from</span> torch.utils.data <span class="hljs-keyword">import</span> DataLoader

trainloader = DataLoader(train, batch_size= <span class="hljs-number">32</span>, shuffle=<span class="hljs-literal">True</span>)
testloader = DataLoader(test, batch_size= <span class="hljs-number">32</span>, shuffle=<span class="hljs-literal">True</span>)

<span class="hljs-comment">#Plotting a Batch of DataLoader</span>
images, labels = iter(trainloader).next()
plt.figure(figsize = (<span class="hljs-number">12</span>,<span class="hljs-number">16</span>))
<span class="hljs-keyword">for</span> e,(img, lbl) <span class="hljs-keyword">in</span> enumerate(zip(images, labels)):
    plt.subplot(<span class="hljs-number">8</span>,<span class="hljs-number">4</span>,e+<span class="hljs-number">1</span>)
    plt.imshow(img[<span class="hljs-number">0</span>])
    plt.title(<span class="hljs-string">f'Class: <span class="hljs-subst">{lbl.item()}</span>'</span>)

plt.subplots_adjust(hspace=<span class="hljs-number">0.6</span>)
</code></pre>
<p>Output:-
<img src="https://i.ibb.co/n8S0NxR/mnist-2.png" alt="fashion-mnist.png" /></p>
<p>Damn, that looks beautiful and correct, well there you go seems like our DataLoaders work as expected. But is it just me or does this seem too messy? I mean it's great we batched the data but the variables seem to be everywhere, it doesn't seem much organized. Well, that's basically where DataModules come in handy 😎.</p>
<h3 id="datamodules">DataModules</h3>
<p>DataModule is a reusable and shareable class that encapsulates the DataLoaders along with the steps required to process data. Creating DataLoaders can get messy that’s why it’s better to club the dataset in the form of DataModule. DataModule has few methods that must define the format of DataModule is as follows:-</p>
<pre><code class="lang-text">import pytorch-lightning as pl

class DataModuleClass(pl.LightningDataModule):
    def __init__(self):
        # Define class attributs here

    def prepare_data(self):
        # Define steps that should be done
        # on only one GPU, like getting data.

    def setup(self, stage=None):
        # Define steps that should be done on 
        # every GPU, like splitting data, applying
        # transform etc.

    def train_dataloader(self):
        # Stage DataLoader for Training Data

    def val_dataloader(self):
        # Stage DataLoader for Validation Data

    def test_dataloader(self):
        # Stage DataLoader for Testing Data
</code></pre>
<p>That seems great so let's go ahead and create DataModule for our Fashion MNIST Data.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pytorch_lightning <span class="hljs-keyword">as</span> pl 

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DataModuleFashionMNIST</span>(<span class="hljs-params">pl.LightningDataModule</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        super().__init__()

        self.dir = <span class="hljs-string">''</span>
        self.batch_size = <span class="hljs-number">32</span>
        self.transform = transforms.Compose([
            transforms.ToTensor()
        ])

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">prepare_data</span>(<span class="hljs-params">self</span>):</span>
        datasets.FashionMNIST(self.dir, train = <span class="hljs-literal">True</span>, download = <span class="hljs-literal">True</span>)
        datasets.FashionMNIST(self.dir, train = <span class="hljs-literal">False</span>, download = <span class="hljs-literal">True</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setup</span>(<span class="hljs-params">self, stage=None</span>):</span>
        data = datasets.FashionMNIST(self.dir,
                                     train = <span class="hljs-literal">True</span>, 
                                     transform = self.transform)

        self.train, self.valid = random_split(data, [<span class="hljs-number">52000</span>, <span class="hljs-number">8000</span>])

        self.test = datasets.FashionMNIST(self.download_dir,
                                               train = <span class="hljs-literal">False</span>,
                                               transform = self.transform)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">train_dataloader</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> DataLoader(self.train, batch_size = self.batch_size)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">val_dataloader</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> DataLoader(self.valid, batch_size = self.batch_size)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_dataloader</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> DataLoader(self.test_data, batch_size = self.batch_size)

data = DataModuleFashionMNIST()
</code></pre>
<p>Perfect that's basically it but if you want an in-depth explanation on them you can refer <a target="_blank" href="https://www.geeksforgeeks.org/understanding-pytorch-lightning-datamodules/"><strong>this article</strong></a> I wrote explaining about DataModules.</p>
<h2 id="lightning-callbacks-and-hooks">Lightning Callbacks &amp; Hooks</h2>
<p>Callbacks are basically programs that contain code that's run when it is required. When and what a callback should do is defined by using Callback <strong>Hooks</strong>, a few of them are on_epoch_end, on_validation_epoch_end, etc. You can maybe define a logic to monitor a metric, save a model, or various other cool stuff. If I have to define callbacks as a meme it'll be the following.</p>
<p><img src="https://i.ibb.co/Bst2x0r/gRqRS4U.png" alt="gRqRS4U.png" /></p>
<p>Well necessary for training but useful for other stuff. There are many inbuilt callbacks that can be used for various important tasks. A few of them are:-</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>CallBack</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><strong>EarlyStopping</strong></td><td><em>Monitor a metric and stop training when it stops improving.</em></td></tr>
<tr>
<td><strong>LearningRateMonitor</strong></td><td><em>Automatically monitors and logs learning rate for learning rate schedulers during training.</em></td></tr>
<tr>
<td><strong>ModelCheckpoint</strong></td><td><em>Save the model periodically by monitoring a quantity.</em></td></tr>
<tr>
<td><strong>Callback</strong></td><td><em>Base Class to define custom callbacks.</em></td></tr>
<tr>
<td><strong>LambdaCallback</strong></td><td><em>Basically Lambda Function of Callbacks.</em></td></tr>
</tbody>
</table>
</div><p>We'll be using the first two for this article but you can refer to docs to learn more about them. Lightning's video tutorials on their website are pretty good.</p>
<h2 id="tpu-hulkified-gpu">TPU - Hulkified GPU?</h2>
<p>TPUs are accelerators used to speed up Machine Learning Tasks. The catch is that they are platform dependant i.e. TensorFlow. TPUs are optimized for Tensorflow mainly which I think is quite selfish given <strong>PyTorch</strong> is so awesome. </p>
<p><img src="https://i.ibb.co/TtgJcwk/5cifez.jpg" alt="5cifez.jpg" /></p>
<p>But we can actually use them in PyTorch by making and passing a <strong>TPU Sampler</strong> in the DataLoader. It's one hell of a messy task you have to replace the device type with <strong>xm.xla_device()</strong> and add 2 extra steps for optimizer and not just that you'll have to install <strong>PyTorch/XLA</strong> to do all that. It goes something like this:-</p>
<pre><code>import torch_xla.core.xla_model as xm

dev = xm.xla_device()

<span class="hljs-comment"># TPU sampler</span>
data_sampler = torch.utils.data.distributed.DistributedSampler(
    dataset,
    num_replicas=xm.xrt_world_size(),
    rank=xm.get_ordinal())

dataloader = DataLoader(dataset, batch_size=32, sampler = data_sampler)

<span class="hljs-comment"># Training loop</span>
for batch in dataloader:
    ...
    xm.optimizer_step(optimizer)
    xm.mark_step()
    ...
</code></pre><p>Man the above code is a mess but in Lightning all that is reduced to a simple single line. All you need to do is pass the number of <strong>tpu_cores</strong> to be you and you are done for the day. Really it's that simple.</p>
<pre><code class="lang-python">trainer = pl.Trainer(tpu_cores = <span class="hljs-number">1</span>)
trainer.fit(model)
</code></pre>
<p>I mean it literally couldn't get any simpler than this but still, there is one more thing that's left to talk about and that is <strong>Loggers</strong>. Let's take a look at that.</p>
<h2 id="loggers">Loggers</h2>
<p>Loggers are a kind of utility that you can use to monitor metrics and hyperparameters and much more cool stuff. In fact you probably already have tried one, <strong>Tensorboard</strong>. Ever heard of it? If you are here chances are you might have. Along with Tensorboard, PyTorch Lightning supports various 3rd party loggers from Weights and Biases, Comet.ml, MlFlow, etc.</p>
<p>In fact, in Lightning, you can use multiple loggers together. To use a logger you can create its instance and pass it in Trainer Class under <strong>logger</strong> parameter individually or as a list of loggers.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> pytorch_lightning.loggers <span class="hljs-keyword">import</span> WandbLogger

<span class="hljs-comment"># Single Logger</span>
wandb_logger = WandbLogger(project=<span class="hljs-string">'Fashion MNIST'</span>, log_model=<span class="hljs-string">'all'</span>)
trainer = Trainer(logger=wandb_logger)

<span class="hljs-comment"># Multiple Loggers</span>
<span class="hljs-keyword">from</span> pytorch_lightning.loggers <span class="hljs-keyword">import</span> TensorBoardLogger
tb_logger = TensorBoardLogger(<span class="hljs-string">'tb_logs'</span>, name=<span class="hljs-string">'my_model'</span>)
trainer = Trainer(logger=[wandb_logger, tb_logger])
</code></pre>
<p>The point is how to log the values? We'll take a look at how you can do that along with applying all the stuff I talked about above.</p>
<h2 id="putting-it-all-together">Putting it All Together</h2>
<p>The Ingredient to a model is the data that you feed it, we talked about DataModules in this article so let's start by creating a <strong>DataModule</strong> for out Fashion MNIST data.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pytorch_lightning <span class="hljs-keyword">as</span> pl 
<span class="hljs-keyword">from</span> torchvision <span class="hljs-keyword">import</span> datasets, transforms

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DataModuleFashionMNIST</span>(<span class="hljs-params">pl.LightningDataModule</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, batch_size = <span class="hljs-number">32</span></span>):</span>
        super().__init__()

        self.dir = <span class="hljs-string">''</span>
        self.batch_size = batch_size
        self.transform = transforms.Compose([
            transforms.ToTensor()
        ])

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">prepare_data</span>(<span class="hljs-params">self</span>):</span>
        datasets.FashionMNIST(self.dir, train = <span class="hljs-literal">True</span>, download = <span class="hljs-literal">True</span>)
        datasets.FashionMNIST(self.dir, train = <span class="hljs-literal">False</span>, download = <span class="hljs-literal">True</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setup</span>(<span class="hljs-params">self, stage=None</span>):</span>
        data = datasets.FashionMNIST(self.dir,
                                     train = <span class="hljs-literal">True</span>, 
                                     transform = self.transform)

        self.train, self.valid = random_split(data, [<span class="hljs-number">52000</span>, <span class="hljs-number">8000</span>])

        self.test = datasets.FashionMNIST(self.download_dir,
                                          train = <span class="hljs-literal">False</span>,
                                          transform = self.transform)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">train_dataloader</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> DataLoader(self.train, batch_size = self.batch_size)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">val_dataloader</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> DataLoader(self.valid, batch_size = self.batch_size)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_dataloader</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> DataLoader(self.test_data, batch_size = self.batch_size)

data = DataModuleFashionMNIST()
</code></pre>
<p>Now let's create our model class and setup logs for the <strong>WandbLogger</strong> and then create a model instance for the same.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> torch <span class="hljs-keyword">import</span> nn, optim
<span class="hljs-keyword">import</span> torch.nn.functional <span class="hljs-keyword">as</span> F

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FashionMNISTModel</span>(<span class="hljs-params">pl.LightningModule</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        super().__init__()
        <span class="hljs-comment"># 28 * 28 * 3</span>
        self.conv1 = nn.Conv2d(<span class="hljs-number">1</span>,<span class="hljs-number">16</span>, stride = <span class="hljs-number">1</span>, padding = <span class="hljs-number">1</span>, kernel_size = <span class="hljs-number">3</span>)
        <span class="hljs-comment"># 14 * 14 * 16</span>
        self.conv2 = nn.Conv2d(<span class="hljs-number">16</span>,<span class="hljs-number">32</span>, stride = <span class="hljs-number">1</span>, padding = <span class="hljs-number">1</span>, kernel_size = <span class="hljs-number">3</span>)
        <span class="hljs-comment"># 7 * 7 * 32</span>
        self.conv3 = nn.Conv2d(<span class="hljs-number">32</span>,<span class="hljs-number">64</span>, stride = <span class="hljs-number">1</span>, padding = <span class="hljs-number">1</span>, kernel_size = <span class="hljs-number">3</span>)
        <span class="hljs-comment"># 3 * 3 * 64</span>

        self.fc1 = nn.Linear(<span class="hljs-number">3</span>*<span class="hljs-number">3</span>*<span class="hljs-number">64</span>,<span class="hljs-number">128</span>)
        self.fc2 = nn.Linear(<span class="hljs-number">128</span>,<span class="hljs-number">64</span>)
        self.out = nn.Linear(<span class="hljs-number">64</span>,<span class="hljs-number">10</span>)

        self.pool = nn.MaxPool2d(<span class="hljs-number">2</span>,<span class="hljs-number">2</span>)
        self.loss = nn.CrossEntropyLoss()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">forward</span>(<span class="hljs-params">self,x</span>):</span>
        x = F.relu(self.pool(self.conv1(x)))
        x = F.relu(self.pool(self.conv2(x)))
        x = F.relu(self.pool(self.conv3(x)))

        batch_size, _, _, _ = x.size()

        x = x.view(batch_size,<span class="hljs-number">-1</span>)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        <span class="hljs-keyword">return</span> self.out(x)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">configure_optimizers</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> optim.Adam(self.parameters())

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">training_step</span>(<span class="hljs-params">self, train_batch, batch_idx</span>):</span>
        x, y = train_batch
        logits = self.forward(x)
        loss = self.loss(logits,y)

        <span class="hljs-comment"># Logging the loss</span>
        self.log(<span class="hljs-string">'train/loss'</span>, loss, on_epoch=<span class="hljs-literal">True</span>)
        <span class="hljs-keyword">return</span> loss

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">validation_step</span>(<span class="hljs-params">self, valid_batch, batch_idx</span>):</span>
        x, y = valid_batch
        logits = self.forward(x)
        loss = self.loss(logits,y)

        <span class="hljs-comment"># Logging the loss</span>
        self.log(<span class="hljs-string">'valid/loss'</span>, loss, on_epoch=<span class="hljs-literal">True</span>)
        <span class="hljs-keyword">return</span> loss
</code></pre>
<p>As you can see in the above code we are using self.log() to log our loss values for which chart will be generated. Now let's create our logger and fit our trainer.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> pytorch_lightning.loggers <span class="hljs-keyword">import</span> WandbLogger

model = FashionMNISTModel()
wandb_logger = WandbLogger(project=<span class="hljs-string">'Fashion MNIST'</span>, log_model=<span class="hljs-string">'all'</span>)

trainer = pl.Trainer(max_epochs=<span class="hljs-number">10</span>, tpu_cores = <span class="hljs-number">1</span>, logger = wandb_logger)
wandb_logger.watch(model)

trainer.fit(model, data)
</code></pre>
<p><img src="https://i.ibb.co/0jRwfD8/Screenshot-from-2021-06-08-20-58-37.png" alt="Screenshot from 2021-06-08 20-58-37.png" /></p>
<p>Once you run the above code the logs will be plotted in runtime. I am plotting loss values using the <strong>self.log()</strong> and logging gradients using <strong>watch()</strong>.</p>
<p>If you get <em>MisconfigurationException: No TPU devices were found.</em> then run the following command to fix it.</p>
<pre><code class="lang-text">%%capture
!curl https://raw.githubusercontent.com/pytorch/xla/master/contrib/scripts/env-setup.py -o pytorch-xla-env-setup.py &gt; /dev/null
!python pytorch-xla-env-setup.py --version nightly --apt-packages libomp5 libopenblas-dev &gt; /dev/null
!pip install pytorch-lightning &gt; /dev/null
</code></pre>
<p>Since the model is extremely simple I didn't use any callbacks but you can use if you like. In Learning Rate Monitor Callback you need to have a scheduler to make it work and pass the Model Checkpoint Callback in <strong>checkpoint_callback</strong> instead of <strong>callback</strong>.</p>
<h2 id="from-me-to-you">From Me to You...</h2>
<p>Wow, that seemed like an exciting ride. Honestly, I think Lightning has many cool stuff that a person can utilize the fact that we can use all these while keeping it as close to PyTorch proves how powerful it is. I hope now you are convinced that Lightning is a great tool to be learned and used.</p>
]]></content:encoded></item><item><title><![CDATA[Class Imbalance comes in Like a Lion]]></title><description><![CDATA[We'll see some of the techniques you can use to modify your data to balance out the class ratio and we'll see how to tackle imbalance in different domains.]]></description><link>https://krypticmouse.hashnode.dev/class-imbalance-comes-in-like-a-lion</link><guid isPermaLink="true">https://krypticmouse.hashnode.dev/class-imbalance-comes-in-like-a-lion</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[Data Science]]></category><category><![CDATA[data analysis]]></category><category><![CDATA[data]]></category><category><![CDATA[Deep Learning]]></category><dc:creator><![CDATA[Herumb Shandilya]]></dc:creator><pubDate>Sat, 05 Jun 2021 17:12:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622912007891/L2hp8MGyr.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>In a world without class imbalance we might've been heroes. </p>
<p>- Neural Networks</p>
</blockquote>
<p>Keeping aside the fact that I butchered one of the greatest Video Game quotes of all time class imbalance can be a tricky thing to handle especially if you are a beginner. When I first encountered class imbalance I treated it normally, I know right, and not just that I measured the accuracy to judge the performance. Needless to say, that went quite badly, and to avoid this happening to you let me help out in avoiding an embarrassing situation in front of your teacher or whoever you report to. </p>
<p>Class Imbalance refers to a condition where the no. of data points corresponding to a class overpowers the other in a significant way. This could happen cause of bias towards a particular class during data collection, error during labeling, etc. I mean the cause doesn't matter once the data is served so all you can do now is see what you can do with whatever you have. </p>
<p>We'll see how to tackle class imbalance in different domains like structured data, NLP, and CV. We'll see some of the techniques you can use to modify your data to balance out the class ratio and we'll talk about how you can fix this thing on a model level without modifying the data itself.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622800140013/qGeorNIZD.png" alt="i have too many books.png" /></p>
<h2 id="loading-our-data">Loading Our Data</h2>
<p>I believe that the correct way to learn a concept is by applying what you learn in theory and that's why I'll be putting code for you to see how we are actually going to apply what we are talking about. For the purpose of this article I've decided to use the classic dataset used to teach class imbalance i.e. <a target="_blank" href="https://www.kaggle.com/mlg-ulb/creditcardfraud">Credit Card Fraud Detection</a>. </p>
<pre><code class="lang-python">df = pd.read_csv(<span class="hljs-string">'/kaggle/input/creditcardfraud/creditcard.csv'</span>)

X = df.drop(<span class="hljs-string">'Class'</span>, axis = <span class="hljs-number">1</span>)
Y = df[<span class="hljs-string">'Class'</span>]

Y.value_counts()
</code></pre>
<p>Output:-</p>
<pre><code class="lang-text">0    284315
1     492
Name: Class, dtype: int64
</code></pre>
<p>I guess it's safe to say that our data is messed up. YAY! So now that we have our data let's get some action.</p>
<h2 id="choosing-the-correct-metric">Choosing The Correct Metric</h2>
<p>First things first, whenever you see class imbalance you have to ditch Accuracy then and there no questions asked. Think about it you give your model data to tell if a patient is diabetic or not but the data only has 10% samples for diabetic entries, which means the model can attain 90% accuracy just by predicting not diabetic every time. What you wanna see is how well the model can classify the diabetic entries or our minority class. For this, we can use various metrics:-</p>
<ul>
<li><strong>Precision: </strong> Out of all entries classified as class A how many were correctly classified.</li>
<li><strong>Recall: </strong> How many entries of class A was our model able to recall correctly.</li>
<li><strong>F1-Score: </strong> Harmonic mean of Precision and Recall.</li>
<li><strong>ROC-AUC Score: </strong> Area under Curve of plot between Specificity and Sensitivity Values at different thresholds.</li>
<li><strong>PR Curve: </strong> Plot between Precision and Recall Values at different thresholds.</li>
</ul>
<h3 id="mcc-and-kappa-score">MCC and Kappa Score</h3>
<p>So you get the gist right, <strong>Accuracy is not always accurate</strong>. But apart from the above-mentioned, I wanna talk about one more matrix. The Dark Horse of the Evaluation Metrics and arguably the best classification metric <strong>Matthew's Coherent Coefficient</strong> or MCC Score if you may. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622802585385/KKh1JS7cpP.png" alt="1_8E2rPn_ccOqGuPYj1gBTAg.png" /></p>
<p>The above metrics are fine too but MCC Score is much more reliable since it gives a good score only when all the portions of the confusion matrix give good results i.e. TP, FP, TN, and FN. </p>
<p>MCC is designed for binary classification but it can be used for multi-class classification using micro or macro averaging. We also have Kappa Score that can be used for both imbalanced and multi-class data. Note that there are many papers that argue the reliability of Kappa score and many papers that defend it. Mostly revolving around its unwanted behavior but let's leave it a topic for another blog.</p>
<h3 id="scoring-the-baseline-results">Scoring The Baseline Results</h3>
<p>Well, I hope you were able to grasp the importance of proper metrics when dealing with an imbalanced dataset. So let's start by checking the performance of our baseline model. Now in order to score our model, we'll have to split the data into training and testing splits but our data is imbalanced so we can't just do random splits. We need the data to retain the original class ratio and for that, we have the <strong>stratify</strong> parameter in <strong>train_test_split</strong> itself. </p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.model_selection <span class="hljs-keyword">import</span> train_test_split

x_train, x_test, y_train, y_test = train_test_split(X, Y, 
                                                    test_size = <span class="hljs-number">0.25</span>, 
                                                    random_state = <span class="hljs-number">1</span>, 
                                                    stratify = Y)
</code></pre>
<p>Well that was easy, wasn't it? Now let's go ahead and train our baseline model and check its baseline metrics using classification_report and confusion_matrix.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.ensemble <span class="hljs-keyword">import</span> RandomForestClassifier
<span class="hljs-keyword">from</span> sklearn.metrics <span class="hljs-keyword">import</span> classification_report, confusion_matrix

clf = RandomForestClassifier()
clf.fit(x_train, y_train)

y_pred = clf.predict(x_test)

print(<span class="hljs-string">f'Confusion Matrix:-\n <span class="hljs-subst">{confusion_matrix(y_test,y_pred)}</span>\n'</span>)
print(classification_report(y_test, y_pred))
</code></pre>
<p>Output:-</p>
<pre><code class="lang-text">Confusion Matrix:-
 [[71073     6]
 [   17   106]]

              precision    recall  f1-score   support

           0       1.00      1.00      1.00     71079
           1       0.95      0.86      0.90       123

    accuracy                           1.00     71202
   macro avg       0.97      0.93      0.95     71202
weighted avg       1.00      1.00      1.00     71202
</code></pre>
<h2 id="choosing-suitable-algorithm">Choosing Suitable Algorithm?</h2>
<p>Now that we understand the importance of metrics in measuring the performance of a model in class imbalance, we can move on and check if there are any algorithms that aren't really bothered by class imbalance. </p>
<p>I mean on paper KNN shouldn't be bothered with class imbalance but there is something <strong>Hellinger Distance Decision Trees</strong>, basically decision trees that use Hellinger Distance as the split criterion. They were created to tackle the effect of imbalance on decision trees.</p>
<p>There is also a way by which you can modify your algorithm to give importance to minority class prediction by the use of class weights. Let's talk more about this cause why not.</p>
<h3 id="cost-sensitive-algorithms">Cost-Sensitive Algorithms</h3>
<p>Please don't be intimidated by the name it's a rather simple concept, basically you assign weights to each class what these signify is that how much will the algorithm be penalized for a misclassification for an entry of a class. There are many algorithms in sklearn that support class weighing and few that don't support it. </p>
<p>The weights are assigned to the class such that the minority class has a higher weight than the majority class. We would expect that the algorithm trained on class weights will perform better as compared to the standard one. </p>
<p>In order to pass weights to the algorithm, you can simply pass the dictionary with key as class and value as the weight to the corresponding key to the <strong>class_weight</strong> parameter. Let's try doing this in our classifier.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.ensemble <span class="hljs-keyword">import</span> RandomForestClassifier
<span class="hljs-keyword">from</span> sklearn.metrics <span class="hljs-keyword">import</span> classification_report, confusion_matrix

clf = RandomForestClassifier(verbose = <span class="hljs-number">100</span>, class_weight = {<span class="hljs-number">0</span>:<span class="hljs-number">600</span>,<span class="hljs-number">1</span>:<span class="hljs-number">1</span>})
clf.fit(x_train, y_train)

y_pred = clf.predict(x_test)

print(<span class="hljs-string">f'Confusion Matrix:-\n <span class="hljs-subst">{confusion_matrix(y_test,y_pred)}</span>\n'</span>)
print(classification_report(y_test, y_pred))
</code></pre>
<p>Output:-</p>
<pre><code class="lang-text">              precision    recall  f1-score   support

           0       1.00      1.00      1.00     71079
           1       0.92      0.88      0.90       123

    accuracy                           1.00     71202
   macro avg       0.96      0.94      0.95     71202
weighted avg       1.00      1.00      1.00     71202
</code></pre>
<p>Recall value seems to have increased a bit that means our cost-sensitive model is able to recall more values from minority class in the testing set. You can try out different combinations to check if you can get better results.</p>
<p>Now one question that may arise in your mind is, what weights should I assign to which class? There is a simple answer to this question i.e. by tuning the weights. You can select a range of values and using GridSearch to find which ones work the best.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622826149673/S0MuEnBme.jpeg" alt="Untitled.jpg" /></p>
<p>Let's say you are a daredevil and wanna tune the weights then, you can try using <strong>compute_class_weight()</strong> utility in sklearn to compute class weights and use them as the weights for the algorithm. In my experience, it rarely gives the best result as compared to tuned ones. But tuning is actually pretty simple, below I'll tell you how to do it and I want you to try it out by redefining the param_grid according to what you think is the best. You can comment on your findings if you like too 😃</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.model_selection <span class="hljs-keyword">import</span> GridSearchCV

param_grid = {
    <span class="hljs-string">'class_weight'</span> : [{<span class="hljs-number">0</span>:<span class="hljs-number">600</span>,<span class="hljs-number">1</span>:<span class="hljs-number">1</span>}, {<span class="hljs-number">0</span>:<span class="hljs-number">700</span>,<span class="hljs-number">1</span>:<span class="hljs-number">1</span>}, {<span class="hljs-number">0</span>:<span class="hljs-number">800</span>,<span class="hljs-number">1</span>:<span class="hljs-number">1</span>}]
}

grid = GridSearchCV(RandomForestClassifier(), param_grid = param_grid)
grid.fit(x_train, y_train)

y_pred = clf.predict(x_test)

print(<span class="hljs-string">f'Confusion Matrix:-\n <span class="hljs-subst">{confusion_matrix(y_test,y_pred)}</span>\n'</span>)
print(classification_report(y_test, y_pred))
</code></pre>
<p>In neural networks to you can train your model with assigned class weights to tackle the issue of class imbalance. The syntax is pretty similar in the sense you just pass the class weights to the network. In Tensorflow you pass weights in the fit() function and in PyTorch you pass weights in the Loss function.</p>
<pre><code class="lang-python"><span class="hljs-comment"># PyTorch - Pass weight tensor in loss function</span>
pytorch_weights = torch.tensor([<span class="hljs-number">0.99</span>, <span class="hljs-number">0.1</span>])
criterion = nn.NLLLoss(weight =  pytorch_weights)

<span class="hljs-comment"># TensorFlow - Pass weight dictionary in fit function</span>
tf_weights = { <span class="hljs-number">0</span> : <span class="hljs-number">99</span>, 
               <span class="hljs-number">1</span> : <span class="hljs-number">1</span> }
model.fit(x_train, y_train, batch_size = <span class="hljs-number">50</span>, class_weight = tf_weights)
</code></pre>
<h2 id="handling-class-imbalance-with-data-modification">Handling Class Imbalance with Data Modification</h2>
<p>No no I'm not talking about modifying the values of the entries but I'm talking about how we can remove or add entries corresponding to a class to the existing data in order to balance the class ratio. There are quite a few ways to go about it and we'll explore almost all of them in-depth. Once you have balanced out the classes it basically you good old classification problem. The ones that we'll learn about are:-</p>
<ul>
<li>Undersampling - Fix for the Lazy</li>
<li>Oversampling - Jugaad</li>
<li>SMOTE - Fix from Logic</li>
<li>ADASYN - SMOTE's Sibling</li>
</ul>
<p>It'll be better If you install <strong>imblearn</strong> library since that's what we'll be using to implement the above. You can install it via the following command:-</p>
<pre><code class="lang-text">pip install imblearn
</code></pre>
<h3 id="undersampling-fix-for-the-lazy">Undersampling - Fix for the Lazy</h3>
<p>Random Undersampling is a way to balance class by removing entries from the majority class randomly. I know right makes no sense, you are basically randomly deleting entries from the majority class. Not many people are fond of this mainly cuz it leads to loss of information, I too think it's stupid to lose that precious labeled data. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622826516604/8mEkvCM4q.png" alt="raw.png" /></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> imblearn.under_sampling <span class="hljs-keyword">import</span> RandomUnderSampler

us = RandomUnderSampler()
x_train, y_train = us.fit_resample(x_train, y_train)

clf = RandomForestClassifier()
clf.fit(x_train, y_train)

y_pred = clf.predict(x_test)

print(<span class="hljs-string">f'Confusion Matrix:-\n <span class="hljs-subst">{confusion_matrix(y_test,y_pred)}</span>\n'</span>)
print(classification_report(y_test, y_pred))
</code></pre>
<p>Output:-</p>
<pre><code class="lang-text">Confusion Matrix:-
 [[68666  2413]
 [    8   115]]

              precision    recall  f1-score   support

           0       1.00      0.97      0.98     71079
           1       0.05      0.93      0.09       123

    accuracy                           0.97     71202
   macro avg       0.52      0.95      0.53     71202
weighted avg       1.00      0.97      0.98     71202
</code></pre>
<p>But, what if we undersample our data smartly? There are ways and algorithms that can be used to removed redundant data and reduce the issue of losing important information. Not just but sometimes a combination of both oversampling and undersampling can achieve good results too. But enough with that let's learn about those smart undersampling methods.</p>
<h4 id="near-miss-undersampling">Near Miss Undersampling</h4>
<p>This type of undersampling basically determines the samples from the majority class that should be retained based on the distance between that sample and minority class samples. It has 3 variations to it:-</p>
<ul>
<li><strong>Version - 1: </strong>  Keeps the ones that have the minimum average distance from the nearest three minority class samples.</li>
<li><strong>Version - 2: </strong>  Keeps the ones that have the minimum average distance from the farthest three minority class samples.</li>
<li><strong>Version - 3: </strong>  Keeps the ones that have the minimum average distance from all minority class samples.</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> imblearn.under_sampling <span class="hljs-keyword">import</span> NearMiss

nm_us = NearMiss(version = <span class="hljs-number">3</span>)
x_train, y_train = nm_us.fit_resample(x_train, y_train)

clf = RandomForestClassifier()
clf.fit(x_train, y_train)

y_pred = clf.predict(x_test)

print(<span class="hljs-string">f'Confusion Matrix:-\n <span class="hljs-subst">{confusion_matrix(y_test,y_pred)}</span>\n'</span>)
print(classification_report(y_test, y_pred))
</code></pre>
<p>Output:-</p>
<pre><code class="lang-text">Confusion Matrix:-
 [[68681  2398]
 [    8   115]]

              precision    recall  f1-score   support

           0       1.00      0.97      0.98     71079
           1       0.05      0.93      0.09       123

    accuracy                           0.97     71202
   macro avg       0.52      0.95      0.54     71202
weighted avg       1.00      0.97      0.98     71202
</code></pre>
<p>I've tried quite a few examples and in most case version 3 really works better as compared to the other 2.</p>
<h4 id="tomek-links-undersampling">Tomek Links Undersampling</h4>
<p>This type of undersampling has a simple yet neat approach it focuses on removing the majority sample of the Tomek link. Tomek link is defined as the points that are closest to each other and both belonging to different classes, kinda like Romeo and Juliet except here only one of them dies, an apology to all R&amp;J fans. Anyways let's try our hand on Tomek links.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> imblearn.under_sampling <span class="hljs-keyword">import</span> TomekLinks

tomek_us = TomekLinks()
x_train, y_train = tomek_us.fit_resample(x_train, y_train)

clf = RandomForestClassifier(verbose = <span class="hljs-number">100</span>)
clf.fit(x_train, y_train)

y_pred = clf.predict(x_test)

print(<span class="hljs-string">f'Confusion Matrix:-\n <span class="hljs-subst">{confusion_matrix(y_test,y_pred)}</span>\n'</span>)
print(classification_report(y_test, y_pred))
</code></pre>
<p>Here since only Tomek links are deleted the class balance isn't completely achieved rather only ambiguous points are removed. </p>
<h3 id="random-oversampling-jugaad">Random Oversampling - Jugaad</h3>
<p>This is the exact opposite of what we did in undersampling instead of removing points from the majority class we explode the minority class by filling data with samples from the minority class chosen at random with repetition and hence achieving class balance. There are ways to explode minority class samples smartly and logically like by generating synthetic data but we'll talk about them shortly.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> imblearn.over_sampling <span class="hljs-keyword">import</span> RandomOverSampler

os = RandomOverSampler()
x_train, y_train = os.fit_resample(x_train, y_train)

clf = RandomForestClassifier(verbose = <span class="hljs-number">100</span>)
clf.fit(x_train, y_train)

y_pred = clf.predict(x_test)

print(<span class="hljs-string">f'Confusion Matrix:-\n <span class="hljs-subst">{confusion_matrix(y_test,y_pred)}</span>\n'</span>)
print(classification_report(y_test, y_pred))
</code></pre>
<p>Output:-</p>
<pre><code class="lang-text">Confusion Matrix:-
 [[71072     7]
 [   17   106]]

              precision    recall  f1-score   support

           0       1.00      1.00      1.00     71079
           1       0.94      0.86      0.90       123

    accuracy                           1.00     71202
   macro avg       0.97      0.93      0.95     71202
weighted avg       1.00      1.00      1.00     71202
</code></pre>
<h3 id="smote-fix-from-logic">SMOTE - Fix from Logic</h3>
<p>SMOTE, or Synthetic Minority Oversampling TEchnique, is a way through which we oversample the data by generating synthetic data based on the provided samples of the minority classes. The steps required to create synthetic data are actually quite simple:-</p>
<ol>
<li>Take samples from the minority class</li>
<li>Join these samples via lines</li>
<li>Pick points that lie on these lines at random until you achieve class balance</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622832428836/1jcbnOKZ3.png" alt="i have too many books (2) (1).png" /></p>
<p>Take the above picture, which took me 30 mins to make, as an example, we only have 4 red points in the minority sample but if we join those points and add points that lie on the red line to the existing dataset then we can balance the class ratio. This basically how SMOTE works. Simple right! </p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> imblearn.over_sampling <span class="hljs-keyword">import</span> SMOTE

smote = SMOTE()
x_train, y_train = smote.fit_resample(x_train, y_train)

clf = RandomForestClassifier(verbose = <span class="hljs-number">100</span>)
clf.fit(x_train, y_train)

y_pred = clf.predict(x_test)

print(<span class="hljs-string">f'Confusion Matrix:-\n <span class="hljs-subst">{confusion_matrix(y_test,y_pred)}</span>\n'</span>)
print(classification_report(y_test, y_pred))
</code></pre>
<p>Output:-</p>
<pre><code class="lang-text">Confusion Matrix:-
 [[71066    13]
 [   14   109]]

              precision    recall  f1-score   support

           0       1.00      1.00      1.00     71079
           1       0.89      0.89      0.89       123

    accuracy                           1.00     71202
   macro avg       0.95      0.94      0.94     71202
weighted avg       1.00      1.00      1.00     71202
</code></pre>
<p>Hmm, that seems fine recall went up a bit but precision took a hit. There are other variates to SMOTE that you can explore and learn about too. But for now, it's time to move on to the next method.</p>
<h3 id="adasyn-smotes-sibling">ADASYN - SMOTE's Sibling</h3>
<p>ADASYN, or Adaptive Synthetic, is a way through which we oversample the data by generating synthetic data based on the density of majority neighbors around a minority sample. The difference between SMOTE and ADASYN is that in ADASYN the no. of samples generated around a point depends on the density distribution r_x of that point whereas in SMOTE all minority samples have equal weights.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622834736808/9Xo5E88eD.png" alt="i have too many books (3) (1).png" /></p>
<p>For example in the above image purple point will have more samples generated around it rather than the green arrow one. Let's understand the steps required in ADASYN:-</p>
<ol>
<li><p>Calculate the no. of points to be generated, denoted by G. Here beta is the balance factor which if kept 1 generates a point to achieve perfect class balance.
$$
G = ( n_M - n_m) * {\beta}
$$
where n_M &lt;- No. of majority class samples and n_m &lt;- No. of minority class samples</p>
</li>
<li><p>For all i that belong to minority class we find the ratio:-
$$
r_i = Δ_i / K
$$
where K is the no. of neighbors and Δ represents the no. of samples belonging to the majority class out of those K neighbors.</p>
</li>
<li><p>Convert the above to probability distribution.
$$
\hat{r_i} = r_i / \sum{r_i}
$$</p>
</li>
<li><p>Calculate the no. of data points to be generated around each minority sample. Then for each minority sample, you generate gᵢ no. of samples. 
$$
g_i = \hat{r_i} * G
$$</p>
</li>
</ol>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> imblearn.over_sampling <span class="hljs-keyword">import</span> ADASYN

adasyn = ADASYN()
x_train, y_train = adasyn.fit_resample(x_train, y_train)

clf = RandomForestClassifier(verbose = <span class="hljs-number">100</span>)
clf.fit(x_train, y_train)

y_pred = clf.predict(x_test)

print(<span class="hljs-string">f'Confusion Matrix:-\n <span class="hljs-subst">{confusion_matrix(y_test,y_pred)}</span>\n'</span>)
print(classification_report(y_test, y_pred))
</code></pre>
<p>Output:-</p>
<pre><code class="lang-text">Confusion Matrix:-
 [[71065    14]
 [   14   109]]

              precision    recall  f1-score   support

           0       1.00      1.00      1.00     71079
           1       0.89      0.89      0.89       123

    accuracy                           1.00     71202
   macro avg       0.94      0.94      0.94     71202
weighted avg       1.00      1.00      1.00     71202
</code></pre>
<h2 id="handling-class-imbalance-in-image-classification">Handling Class Imbalance in Image Classification</h2>
<p>In Image Classification, the usual way to handle class imbalance is to explode the data using Oversampling or via Data Augmentation. In oversampling, it's pretty simple you copy and you replicate like the good old way.</p>
<p>In Oversampling by Data Augmentation, you can generate samples by changing the nature of the image itself. For those who don't know Image Augmentation refers to changing the aspects of an image like its scale, angle orientation, etc. Keep in mind I'm not talking about just applying augmentation to the image but saving those augmentations if you do the first the dataset will be still imbalanced.</p>
<p>Another way to tackle this is by passing class_weights to the CNN model. Now unless you are a person who loves pain chances are you'll be using a CNN model or a pre-trained model for image classification for which we can define class_weights and train the network accordingly.</p>
<h2 id="handling-class-imbalance-in-text-classification">Handling Class Imbalance in Text Classification</h2>
<p>Text Classification for the imbalanced set is also similar, we can use class_weights to define penalty for misclassification of each class. Chances are you might be using LSTM, BERT, etc. for which we can utilize class_weights. </p>
<p>We can also remove duplicate sentences too. Like if you have 2 sentences, "Bag is in the room" and "Bag is in room", welp they are basically the same so we can remove one of them. Removing such duplicate messages will help you reduce the size of your majority class.</p>
<p>The next way is oversampling the google old random way i.e. Random Oversampling or you can explode minority samples with text augmentations. Wait what? Text Augmentations!? I mean in images we rotate, scale up, crop, rotate, etc. but what can we do with text? In text augmentation we start by tokenizing sentences then we can shuffle and rejoin them to generate new texts. We can also replace adjectives, verbs, etc. by its a synonym to generate text with the same meaning.</p>
<p>There is another way where you are converting English text to a language and converting back to English using language translation. </p>
<h2 id="from-me-to-you">From Me to You...</h2>
<p>Boy was that a lot of information to grasp. Imbalance classification can be a pain I mean in a perfect world there would be no imbalance, sadly we live in a world where 4-koma mangas rarely get an anime adaptation, so unfair. The point is where is a will there is a way and I hope I was able to guide you through that way properly. See you in the next article!</p>
]]></content:encoded></item><item><title><![CDATA[Training SVM over Custom Kernels]]></title><description><![CDATA[Can you create a kernel of your own to train SVM on? What are Kernels? What's the role of Gram Matrix? Why do that? Let's understand!]]></description><link>https://krypticmouse.hashnode.dev/training-svm-over-custom-kernels</link><guid isPermaLink="true">https://krypticmouse.hashnode.dev/training-svm-over-custom-kernels</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[Data Science]]></category><category><![CDATA[ML]]></category><category><![CDATA[Artificial Intelligence]]></category><dc:creator><![CDATA[Herumb Shandilya]]></dc:creator><pubDate>Thu, 29 Apr 2021 00:03:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1619654326149/bHB2Bwj0k.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One thing that always intrigued me about ML is that the more you learn about it the more you realize how little you know. One such case that happened to me a few months ago when a person asked me if I could help him in SVM and me being me I was like sure not a big deal. It was a big deal.</p>
<p>Most of us might be familiar with training models. Few of us might be familiar with when to use which model. But when it comes to the details of these models we might fail to utilize them. In SVM, most of us might use the default RBF, a few of us might play with other kernels to find a better model and chosen ones might understand the working and purpose of these kernels. But can you create a kernel of your own?</p>
<p>Let's go ahead and try to understand a bit about how you can create your own kernel and train a simple SVC model over it.</p>
<h2 id="getting-our-data">Getting Our Data</h2>
<p>Every ML Pipeline is basically non-existent without data. So let's start by getting our data. I'm a simple man so for the sake of simplicity I'll just make a dataset using the <strong>make_classification</strong> utility in <strong>sklearn.datasets</strong>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.datasets <span class="hljs-keyword">import</span> make_classification

x,y = make_classification(n_samples = <span class="hljs-number">1000</span>)
print(x.shape, y.shape)
</code></pre>
<p>Now that we have the data all sorted out let's go ahead and understand about working and use of kernels in SVM.</p>
<h2 id="understanding-kernels">Understanding Kernels</h2>
<p>To those who forgot how SVM works, which is nothing to worry about, let's take a walk down the memory. So basically what SVM aims to do is to introduce a hyperplane that divides the data such that the margin by which they are separated is maximized but if you just what to maximize the margin then you might run into cases where its impossible to maximize the margin or even worse outliers affecting the margin size. </p>
<p>So to tackle this we ignore some points and allow the error in order to achieve optimal margin, we call these points <strong>support vectors</strong>. And now the margin is called a soft margin. So your aim is to maximize the soft margin. How much misclassification to allow is determined using cross-validation. This is a nice approach until you run into something I call a not so simple distribution. Take a look at the following not so simple example:-</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1619549309926/PhcWAMCbK.png" alt="image.png" /></p>
<p>So as you can see you can't really separate the above distribution decently with a single hyperplane. But this is where things become interesting, if you map this distribution to a higher dimension you'll be able to do the same. This is where kernels come into play these are mathematical functions that map your distribution to a higher dimension. But these kernel functions only compute the relationship of pair in the distribution as if they were in a higher dimension without actually transforming it and this trick to compute relationships in distribution at higher dimension without transforming it is what we call a <strong>kernel trick</strong>.</p>
<p>Phew, that was a lot of complicated stuff. But how does RBF work? RBF actually maps the data into infinite dimensions, which makes it difficult to visualize. So let's keep that for another article.</p>
<p>So now that we have a bit of an understanding of the use of kernels in SVM let's learn about how we can use a custom one in training them. </p>
<h2 id="my-kernel-my-rules">My Kernel, My Rules</h2>
<p>Every time you create an SVC() instance it has a kernel associated with it that handles the mapping part, if you don't specify it explicitly then it takes the kernel as RBF with looks like the following:-</p>
<p>$$<br />K(x_i,x_j) = e^{-{\gamma}||x_i-x_j||^2}      ,{\forall}{\gamma} &gt; 0 
$$</p>
<p>$$
||x_i-x_j||{\space}is{\space}the{\space}euclidean{\space}distance{\space}between{\space}x_i{\space}and{\space}x_j
$$</p>
<p>If you don't understand what's written above then it's fine you can forget it. The important thing to understand is how it works it takes 2 points and computes the RBF for them and stores them in their location in a gram matrix. Gram Matrix is what we'll use to define relationships among pairs for the given kernel. Now 2 ways to train SVM over custom kernel is to:-</p>
<ul>
<li>Passing the kernel function</li>
<li>Passing Gram Matrix</li>
</ul>
<p>For the innocent souls who are unaware of Gram Matrix, it is basically how your kernel functions are represented, simple as that. If you wanna go into the mathematical details for it feel free to Google. </p>
<h3 id="by-passing-the-kernel-function-as-an-argument">By passing the kernel function as an argument</h3>
<p>Let's now implement a simple Linear Kernel Function and train our model over it. Linear Kernel looks like the following:-</p>
<p>$$
K(x_i,x_j) = x_i.x_j
$$</p>
<p>Simple right? All you have to do is just perform a dot product between the pairs. Let's create a function to do the same.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">linear_kernel</span>(<span class="hljs-params">x_i, x_j</span>):</span>
    <span class="hljs-keyword">return</span> x_i.dot(x_j.T)
</code></pre>
<p>That was simple, wasn't it? Let's go ahead and create 2 classifiers one that uses the linear kernel defined in sklearn and the other that we created and then compare their performance. </p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.svm <span class="hljs-keyword">import</span> SVC
<span class="hljs-keyword">from</span> sklearn.metrics <span class="hljs-keyword">import</span> accuracy_score

clf1 = SVC(kernel = linear_kernel)
clf1.fit(x,y)
print(<span class="hljs-string">f'Accuracy on Custom Kernel: <span class="hljs-subst">{accuracy_score(y, clf1.predict(x))}</span>'</span>)

clf2 = SVC(kernel = <span class="hljs-string">'linear'</span>)
clf2.fit(x,y)
print(<span class="hljs-string">f'Accuracy on Inbuilt Kernel: <span class="hljs-subst">{accuracy_score(y, clf2.predict(x))}</span>'</span>)
</code></pre>
<pre><code class="lang-text">Output:-
Accuracy on Custom Kernel: 0.961
Accuracy on Inbuilt Kernel: 0.961
</code></pre>
<p>Well, the results are the same. That was pretty awesome, wasn't it? Now let's try doing the same using the 2nd method.</p>
<h3 id="by-passing-gram-matrix">By passing Gram Matrix</h3>
<p>You can define your own kernels by either giving the kernel as a function, as we saw in the above example, or by precomputing the Gram matrix. We'll first make a function that makes gram matrix given data and function and then make function to compute RBF.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_gram</span>(<span class="hljs-params">x1, x2, kernel</span>):</span>
    <span class="hljs-keyword">return</span> np.array([[kernel(_x1, _x2) <span class="hljs-keyword">for</span> _x2 <span class="hljs-keyword">in</span> x2] <span class="hljs-keyword">for</span> _x1 <span class="hljs-keyword">in</span> x1])

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">RBF</span>(<span class="hljs-params">x1, x2, gamma  = <span class="hljs-number">1</span></span>):</span>
    <span class="hljs-keyword">return</span> np.exp(-gamma*np.linalg.norm(x1-x2))
</code></pre>
<p>Now that we have pre-requisites all set let's train our models and compare. Two things that'll change is:-</p>
<ul>
<li>We'll pass <strong>kernel = 'precomputed'</strong></li>
<li>We'll pass the data as gram matrix while passing data in fit() or predict() function</li>
</ul>
<p>Now things are a bit different if you have a testing set. For example, if we have x_train and x_test then gram matrix to pass in fit() is computed between x_train and x_train but for predicting on x_test it is computed between x_test and x_train.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> sklearn.model_selection <span class="hljs-keyword">import</span> train_test_split

x_train, x_test, y_train, y_test = train_test_split(x, y, stratify = y)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_gram</span>(<span class="hljs-params">x1, x2, kernel</span>):</span>
    <span class="hljs-keyword">return</span> np.array([[kernel(_x1, _x2) <span class="hljs-keyword">for</span> _x2 <span class="hljs-keyword">in</span> x2] <span class="hljs-keyword">for</span> _x1 <span class="hljs-keyword">in</span> x1])

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">RBF</span>(<span class="hljs-params">x1, x2, gamma  = <span class="hljs-number">1</span></span>):</span>
    <span class="hljs-keyword">return</span> np.exp(-gamma * np.linalg.norm(x1-x2))

clf1 = SVC(kernel = <span class="hljs-string">'precomputed'</span>)
clf1.fit(get_gram(x_train, x_train, RBF), y_train)
print(<span class="hljs-string">f'Accuracy on Custom Kernel: <span class="hljs-subst">{accuracy_score(y_test, clf1.predict(get_gram(x_test, x_train, RBF)))}</span>'</span>)

clf2 = SVC(kernel = <span class="hljs-string">'rbf'</span>)
clf2.fit(x_train,y_train)
print(<span class="hljs-string">f'Accuracy on Inbuilt Kernel: <span class="hljs-subst">{accuracy_score(y_test, clf2.predict(x_test))}</span>'</span>)
</code></pre>
<pre><code class="lang-text">Accuracy on Custom Kernel: 0.912
Accuracy on Inbuilt Kernel: 0.904
</code></pre>
<h1 id="code">Code</h1>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> sklearn.svm <span class="hljs-keyword">import</span> SVC
<span class="hljs-keyword">from</span> sklearn.metrics <span class="hljs-keyword">import</span> accuracy_score
<span class="hljs-keyword">from</span> sklearn.datasets <span class="hljs-keyword">import</span> make_classification
<span class="hljs-keyword">from</span> sklearn.model_selection <span class="hljs-keyword">import</span> train_test_split

x,y = make_classification(n_samples = <span class="hljs-number">1000</span>)
x_train, x_test, y_train, y_test = train_test_split(x, y, stratify = y)

<span class="hljs-comment"># Method 1</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">linear_kernel</span>(<span class="hljs-params">x_i, x_j</span>):</span>
    <span class="hljs-keyword">return</span> x_i.dot(x_j.T)

clf1 = SVC(kernel = linear_kernel)
clf1.fit(x_train,y_train)
print(<span class="hljs-string">f'Accuracy on Custom Kernel: <span class="hljs-subst">{accuracy_score(y_test, clf1.predict(x_test))}</span>'</span>)

clf2 = SVC(kernel = <span class="hljs-string">'linear'</span>)
clf2.fit(x_train, y_train)
print(<span class="hljs-string">f'Accuracy on Inbuilt Kernel: <span class="hljs-subst">{accuracy_score(y_test, clf2.predict(x_test))}</span>'</span>)


<span class="hljs-comment"># Method 2</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_gram</span>(<span class="hljs-params">x1, x2, kernel</span>):</span>
    <span class="hljs-keyword">return</span> np.array([[kernel(_x1, _x2) <span class="hljs-keyword">for</span> _x2 <span class="hljs-keyword">in</span> x2] <span class="hljs-keyword">for</span> _x1 <span class="hljs-keyword">in</span> x1])

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">RBF</span>(<span class="hljs-params">x1, x2, gamma  = <span class="hljs-number">1</span></span>):</span>
    <span class="hljs-keyword">return</span> np.exp(-gamma * np.linalg.norm(x1-x2))

clf1 = SVC(kernel = <span class="hljs-string">'precomputed'</span>)
clf1.fit(get_gram(x_train, x_train, RBF), y_train)
print(<span class="hljs-string">f'Accuracy on Custom Kernel: <span class="hljs-subst">{accuracy_score(y_test, clf1.predict(get_gram(x_test, x_train, RBF)))}</span>'</span>)

clf2 = SVC(kernel = <span class="hljs-string">'rbf'</span>)
clf2.fit(x_train,y_train)
print(<span class="hljs-string">f'Accuracy on Inbuilt Kernel: <span class="hljs-subst">{accuracy_score(y_test, clf2.predict(x_test))}</span>'</span>)
</code></pre>
<h2 id="parting-words">Parting Words</h2>
<p>Well, how about that our kernel actually performed well. Noice! Now you know how you can train SVM over a custom kernel. You can try and implement other kernels like Thin-Plate, Cauchy, and other kernels with intimidating names. Using custom kernels isn't usually done practically and in my experience, it's probably because custom ones take a lot of time to train and predict especially if you go with the gram matrix approach. But there is no harm in learning about it right? With this, I congratulate you on learning something new and now you can go ahead and try one yourself. The next article is gonna be especially interesting it's about probably the most popular algo but with a twist of our own. See you soon. </p>
]]></content:encoded></item></channel></rss>