<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Akhil Shekkari on Medium]]></title>
        <description><![CDATA[Stories by Akhil Shekkari on Medium]]></description>
        <link>https://medium.com/@akhil.masters21?source=rss-d6ae1b1ec945------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*88jFM4Foo3_4o8HE</url>
            <title>Stories by Akhil Shekkari on Medium</title>
            <link>https://medium.com/@akhil.masters21?source=rss-d6ae1b1ec945------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:17:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akhil.masters21/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building GPT From First Principles: Code and Intuition]]></title>
            <link>https://pub.towardsai.net/building-gpt-from-first-principles-code-and-intuition-87b12ee0ec3d?source=rss-d6ae1b1ec945------2</link>
            <guid isPermaLink="false">https://medium.com/p/87b12ee0ec3d</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Akhil Shekkari]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 22:02:19 GMT</pubDate>
            <atom:updated>2025-04-21T22:02:19.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBtyV_9UbWp7M-puyBsTyQ.png" /><figcaption>Figure — 0</figcaption></figure><p>The main goal of this blog post would be to Understand each component inside GPT with Intuition and be able to Code it in Plain PyTorch.</p><p>Please have a look at the below two Figures.</p><ol><li>Our Implementation will heavily follow the Figure-1.</li></ol><p>2. I will be taking lots of Ideas and concepts from Figure - 2<br>(taken from Anthropic’s paper on <a href="https://transformer-circuits.pub/2021/framework/index.html">https://transformercircuits.pub/2021/framework/index.html</a> ). we will use this Figure for our Intuition and Understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eUO9x3UfZn2cai6J.png" /><figcaption>Figure — 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MdGkQlz8QDH5bGpR.png" /><figcaption>Figure — 2</figcaption></figure><p>For Every component, I will go over the theory required. This is important because we have to understand why that particular component / concept is used. Next I will go over coding part.</p><p>Lets look at all the Individual components of a Transformer:</p><p>1. Residual Stream(Also Known as Skip Connections)<br>2. Embedding Matrix<br>3. Layer Normalization<br>4. Positional Encoding<br>5. Self Attention Mechanism(Causal Masking)<br>6. Multi — Layer Perceptron<br>7. UnEmbedding Matrix</p><blockquote>Before looking at Residual Stream, It is always good to approach concepts with an example in mind. One of the main reason I came across when people say they find it difficult to code is, <strong>the problem with input output dimensions</strong>. Before and After every Transformation, we should know how the vector changes and its dimension changes.</blockquote><p>Let the example sentence be <strong><em>“Messi is the greatest of all time”. <br></em></strong>For this example, there are 7 tokens(1 word = 1 token for simplicity). let us take 1 token can be represented in 50 dimensions. we call this <strong><em>d_model.<br></em></strong> Batch size is usually the no. of examples we feed to model at given point of time. since we are working with demo example and we have only one example, let us consider a <strong><em>batch_size</em></strong> of 1.Let us Assume max length of any sentence in our dataset is less than or equal to 10. we call this <strong><em>seq_len</em></strong>. Let the total no. of tokens in our vocabulary is 5000. we call this <strong><em>d_vocab</em></strong>.</p><p>So the Configurations of our toy example is:</p><p>d_model = 50<br>d_vocab = 5000</p><p>Note: The above config is for toy example. In our Code, we will be working with Actual GPT level Configs. (See Below)</p><p>Let’s define our Config<br>Note: There are lot oh hyper parameters, which you haven’t seen. But don’t worry, we will cover all of them in later parts of the blog</p><pre>from dataclasses import dataclass<br>## lets define all the parameters of our model<br>@dataclass<br>class Config:<br>    d_model: int = 768<br>    debug: bool = True<br>    layer_norm_eps: float = 1e-5<br>    d_vocab: int = 50257<br>    init_range: float = 0.02<br>    n_ctx: int = 1024<br>    d_head: int = 64<br>    d_mlp: int = 3072<br>    n_heads: int = 12<br>    n_layers: int = 12<br>cfg = Config()<br>print(cfg)</pre><p>Note that @dataclass is simplifying a lot of stuff for us. With @dataclass we get constructor and a clean output representation when we want to print the parameters of that class. No Need of huge boilerplate code. Without that, we would have to write the same class like this.</p><pre>class Config:<br>    def __init__(self, d_model=768, d_vocab=50257):<br>        self.d_model = d_model<br>        self.d_vocab = d_vocab<br><br>    def __repr__(self):<br>        return f&quot;Config(d_model={self.d_model}, d_vocab={self.d_vocab})&quot;</pre><h3><strong>Some Common Implementation details for all the Components:</strong></h3><p>1. For Every Component , we define a class. <br>2. Every Class needs to subclass<strong> nn.Module</strong>. This is important for many reasons like storing model parameters, using helper functions etc., You can read more about this at <a href="https://pytorch.org/tutorials/beginner/nn_tutorial.html">https://pytorch.org/tutorials/beginner/nn_tutorial.html</a><br>3. super().__init__() makes sure the constructor of nn.Module gets called. <a href="https://www.geeksforgeeks.org/python-super-with-__init__-method/">https://www.geeksforgeeks.org/python-super-with-__init__-method/</a><br>4. We then pass config obj to that class, to set values for our parameters as required.</p><h3>What is Embedding matrix ?</h3><p>This is just the plain lookup table. You look for an embedding vector of a particular token.</p><h4><strong>Questions to ask before coding:</strong></h4><p>Q. What is the Input for Embedding Matrix ? <br>A. <strong>Int[Tensor, ‘batch position’] <br></strong>Here [batch, position] represent dimensions. position refers to token postion.</p><p>Q. What is the Output for Embedding Matrix ?<br>A. <strong>Float[Tensor, ‘batch seq_len d_model’]</strong><br>Returns corresponding embedding vectors in the above shape.</p><pre>class Embed(nn.Module):<br>    def __init__(self, cfg: Config):<br>        super().__init__()   <br>        self.cfg = cfg<br>        self.W_E = nn.Parameter(t.empty((cfg.d_vocab, cfg.d_model)))<br>        nn.init.normal_(self.W_E, std = self.cfg.init_range)<br>    def forward(self, tokens: Int[Tensor, &#39;batch position&#39;]) -&gt; Float[Tensor, &#39;batch seq_len d_model&#39;]:<br>        return self.W_E[tokens]</pre><p>Every trainable parameter in a neural network needs to be tracked and updated based on gradients. PyTorch simplifies this with nn.Parameter().<br>Any tensor wrapped in nn.Parameter is automatically registered as a trainable weight.</p><p>nn.init.normal_ fills the tensor with values drawn from a <strong>normal distribution</strong> (a.k.a. Gaussian), in-place.</p><p>Our Embedding matrix will be of the shape (d_vocab, d_model). Intuitively, we can read it as, for every token the matrix row will represent its corresponding embedding vector.</p><h3>What is Positional Embedding ?</h3><p>This can also be thought of as a lookup table. Here Instead of token Ids, we have numbers/positions.Positional Embedding Refers to a <strong>learned vector</strong> assigned to each position (like a token embedding).Think of this as model learns that certain positions have certain tokens and relationships between them which is useful for attention tasks downstream.</p><h4>Small Clarification:</h4><p>In the original paper “Attention is all you Need”, authors came up with <strong>Positional Encoding</strong>. It’s <strong>not learned</strong> it’s a fixed function (based on sine and cosine) you add to the input embeddings. In our GPT, we use Positional Embedding.</p><h4>More Intuition:</h4><p>For the example<br><strong>&quot;Akhil plays football.&quot;<br></strong>Positional embeddings evolve such that:<br>pos[0] → helps identify &quot;Akhil&quot; as the subject<br>pos[1] → contributes to verb detection<br>pos[2] → contributes to object prediction</p><h4>Questions to ask before coding:</h4><p>Q. What is the Input for Positional Embedding ? <br>A. <strong>Int[Tensor, ‘batch position’] <br></strong>Here [batch, position] represent dimensions. position refers to token postion.</p><p>Q. What is the Output for Positional Embedding ?<br>A. <strong>Float[Tensor, ‘batch seq_len d_model’]</strong><br>Returns corresponding embedding vectors in the above shape.</p><pre>class PosEmbed(nn.Module):<br>    def __init__(self, cfg: Config):<br>        super().__init__()<br>        self.cfg = cfg<br>        self.W_pos = nn.Parameter(t.empty((cfg.n_ctx, cfg.d_model)))<br>        nn.init.normal_(self.W_pos, std=self.cfg.init_range)<br><br>    def forward(self, tokens: Int[Tensor, &quot;batch position&quot;]) -&gt; Float[Tensor, &quot;batch position d_model&quot;]:<br>        batch, seq_len = tokens.shape<br>        return einops.repeat(self.W_pos[:seq_len], &quot;seq d_model -&gt; batch seq d_model&quot;, batch=batch)</pre><p>Here n_ctx is the context length of our model. That means at any given time, we will have atmost of n_ctx number token to be positioned.</p><p>In the forward pass, we slice out the relevant position vectors from our learned embedding matrix, and repeat them across the batch. This gives us a tensor of shape [batch, seq_len, d_model], so each token gets a learnable embedding for its position — which we can then add to the token embeddings.</p><h3><strong>What is a Residual Stream ?</strong></h3><p>The straight path from Embed to UnEmbed from Figure — 2. You can kind of think of this as a central part in a Transformer. Information inside this stream flows forward. By forward, I mean from Embedding stage to UnEmbedding stage.</p><p>The tokens will be represented with their corresponsing embeddings via the Embedding Table. These Embeddings then enter the Residual Stream.</p><p>We represent the example <strong>Messi is the greatest of all time</strong>, inside the residual stream in the following dimensions.</p><p>[batch_size, seq_len, d_model] ==&gt; [1, 10, 50]</p><p>(since each token is 50 dimensional vector, and we have 7 tokens. Here we pad the remaining 3 tokens with zeros to maintain dimensions.)</p><p>Next Steps In general,</p><ol><li>Input gets sent to LayerNorm</li><li>Attention Heads, Read Information from this Residual Stream. Attention heads are responsible for moving information within tokens, based on Attention Matrix. (More on this in Attention Section)</li><li>MLP does explicit read and write operations(new vectors) onto this Residual stream. They can also delete information from Residual Stream. <br>(Will explain more on this in later sections)</li></ol><h4>What is Layer Normalization ?</h4><p>Fundamental reason why we do normalization is to keep the data flowing nicely through gradients without gradients vanishing or exploding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*wLudxejoDzLOYV1J" /><figcaption>Figure — 5</figcaption></figure><p>From Figure — 5 , we can see two hyper parameters. These are Gamma(scaling factor) and beta(shifting factor). We make the values inside our embedding vector in Normalized form. E[x] is mean. Then we allow the model a little bit of room as training progresses for the purpose of Scaling and Shifting. we can see small epsilon in order to avoid division by zero error.</p><h4>Questions to Ask:</h4><p>Q. What does Layer Norm take as input ? <br>A. It takes the residual after attention. [Batch posn d_model]</p><p>Q. What does it return ?<br>A. It just normalizes existing values on the embedding vector. Doesn’t add anything new. So returns normalized values.</p><p><strong>Note:</strong> dim = -1 denotes perform operations on the last dimension. Here last dimension is d_model. So, we take mean and varience along the embedding vector of each token independently.</p><pre>### LayerNorm Implementation<br>class LayerNorm(nn.Module):<br>    def __init__(self, cfg: Config ): ### has the x input vector<br>        super().__init__()<br>        self.cfg = cfg<br>        self.w = nn.Parameter(t.ones(cfg.d_model)) ## these are gamma and beta<br>        self.b = nn.Parameter(t.zeros(cfg.d_model)) ## learnable</pre><pre>    def forward(self, residual: Float[Tensor, &#39;batch posn d_model&#39;]) -&gt; Float[Tensor, &#39;batch posn d_model&#39;]:<br>        residual_mean = residual.mean(dim = -1, keepdim=True)<br>        residual_std = (residual.var(dim = -1, keepdim=True, unbiased=False)+ cfg.layer_norm_eps).sqrt()<br>        residual = (residual - residual_mean) / residual_std<br>        residual = residual * self.w + self.b<br>        return residual</pre><h3>Multi Head Attention:</h3><p>Okay. Let’s think in simple terms first. Before talking about Multiple Attention Heads, let us understand what happens in a Single Attention Head.</p><p><strong>Questions to Ask:</strong></p><p>Q. What does an Attention Head get as an Input ? <br>A. The Attention head reads what is present in residual stream. i.e., <strong>Float [batch seq_len d_model]. </strong>From our toy examples, this might be one of the examples like “<strong>Messi is the greatest of all time</strong>”</p><p>Q. After the completion if Self Attention Process(from the attention block), what does the output look like ? <br>A. <strong>Float[Tensor, ‘batch seq_len d_model’]. </strong>The output is still the same example, but there is a lot of information movement. Let’s go through that in detail.</p><p><strong>Information Movement:(Intuition)</strong></p><p>Let&#39;s take two tokens from above.<br>(for our convenience, we represent each token in 4 dimensions.)</p><p>Below is the state of embedding vectors before entering the attention block.</p><p>Messi→ <strong>[0.1 0.9 2.3 7.1]<br></strong>greatest → <strong>[2.1 4.4 0.6 1.8]</strong></p><blockquote><strong>Once these tokens enter into Attention block, tokens start to attend to the tokens came before in order to include more context and change its representation. This is called Causal Self Attention.</strong></blockquote><p>Messi is the greatest of all time.<br>In this example, when greatest wants to encode some context inside of it, it can only use the context from the words Messi, is and the. From these words, the representation of greatest changes. After Attention,</p><p>Messi→ <strong>[0.1 0.9 2.3 7.1]<br></strong>greatest → <strong>[0.2 1.1 0.6 1.8] (changed representation)</strong></p><p>what does that mean ? Look at the greatest vector. Now It represents some “Messi” inside of it. This is kinda like while constructing the embedding vector for “greatest” it is referring to a bit of Messi. This is what is information Movement.</p><p>But still, we want to know how this process exactly happens.</p><p>Let me introduce few Matrices which are important in this process. In the literature, these are named as Queries, Keys and Values.</p><p>Q = Input * Wq<br>K = Input * Wk<br>V = Input * Wv</p><p>Here Input is our example “<strong>Messi is the greatest of all time</strong>”. The Idea of Q, K and V are to do linear transformation of Input into a different space where these Inputs are represented in more meaningful way. Let&#39;s see the dimensions of these matrix multiplications on our toy example.</p><p>Input/redisual = [1 10 50] <strong>[batch seq d_model]</strong></p><p><strong>“Wq”</strong> matrix dimension depends on how many heads we want to have in our model. This is a very important statement because, if we decide to have only one attention head, then we can have <br>Wq = <strong>[n_head, d_model, d_model]</strong> ==&gt; [1, 50,50]</p><p>If we decided to have n_heads, then the dimension will be [d_model/n_heads]. We represent this quantity as d_head.</p><p>So, if we want to have 5 heads, The dimensions of <strong>Wq</strong> will be <br><strong>[n_head, d_model, d_head]</strong> ==&gt; [5, 50, 10].</p><p>Lets say we want to have 5 heads, then</p><blockquote><strong>Q = [1 10 50] * [5, 50, 10] ==&gt;[batch seq d_model] * [n_head d_model d_head] ==&gt; [1 10 5 10] [Batch seq_len n_head d_head]</strong></blockquote><p>The extra dimension in the beginning is batch. For Q, K and V we will clearly see how all of this fits together in a diagram.</p><p>The same applies for K and V matrices. First let’ s talk about K.</p><blockquote><strong>K = [1 10 50] * [5 50 10] ==&gt; [1 10 5 10]</strong></blockquote><p>Attention is calculated by multiplying the Matrices Q and K. Remember, Attention matrix will always be a Square Matrix.</p><p>Please look at the diagram I made. I tried to communicate what do those dimensions even mean. Look at the left part. <strong>[Batch seq d_head d_model]</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-tK7VP4KKVdFZHY420MCWQ.png" /><figcaption>Figure — 3</figcaption></figure><p>I took two example sentences.</p><p>1. I good<br>2. You bad</p><p>In Left representation, for one batch we are having two examples. Of those two examples, we have 2 seq tokens per example. For each token, we have all the heads which is like full d_model dimension. we are not computing attention per head.</p><p>But, we want it such that for every batch , and for every head we want those tokens to be represented by different Attention heads parallely. Right side of the representation helps in that. That is the reason while computing attention, we permute the shapes. (hope this helps!!!)</p><p>Note: Don’t worry all of this transformation can be done very intuitively through einsum. you will see this in coding.</p><p>Now that we have understood, how attention is computed, let’s get back to our Messi example.</p><p>Earlier we talked about how “greatest” would attend to “Messi”. we get a [10,10] matrix of all words of our toy example attending to all the other words.</p><p>Here After getting the attention matrix, we apply causal masking to prevent words attending to future words. “greatest” cannot attend to “time”. After that, we apply Softmax on Attention Matrix. Softmax gives us a score that would sum to 1 along that row. <br>For the word greatest, it would tell how much percent it should attend to <strong>“Messi”</strong>, how much to <strong>“is”</strong> and How much to <strong>“the”</strong> and itself.</p><p>I took some other example from google to make things visually simple. You can easily connect this with our Messi example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bAkF8necHvJ9VZiB.jpg" /><figcaption>Figure — 4</figcaption></figure><p>Once this is done, next step is to Multiply this matrix with our Value vector.<br>As I discussed above, value vector will also be nothing but linear transformation of Input to another Space.</p><p>V = Input * Wv ==&gt; [1 10 50] * [5 50 10] ==&gt; [1 10 5 10]</p><blockquote><strong>Z = V * A==&gt; [batch seq_len n_head d_head] * [batch n_head q_seq k_seq] ==&gt; [1 10 5 10] * [1 5 10 10] ==&gt; [1 10 5 10] [batch seq_len n_head d_head]</strong></blockquote><p>Again, once you look at einsum code, this is self explanatory.</p><p>Z is the output from 1 head. We stack all these outputs of [1 10 5 10] horizontally. There are 5 heads. so the result becomes [1 10 5 50]. <br>The concatenation of all these heads is then multiplied with one final Output Matrix(Wo) which can be intuitively thought of as learning to represent how to combine all these outputs from different heads.</p><blockquote><strong>(Z from all the heads) * Wo <br>[1 10 5 50] * [5 10 50][n_head d_head d_model]==&gt; [1 10 50]</strong></blockquote><p>This is how information is moved in between tokens. I know there are a lot of dimensions here, but this is the core part. once you grab gist of it, everything looks straighforward. Now the information is moved inside the Residual Stream. Look at the code for Implementing Attention below. There are bias initializations which are self explanatory.</p><p><strong>Note: I use “posn” and “seq_len” interchangeably. They are the same.</strong></p><p>Implementation details:</p><ol><li>Regarding implementing causal mask is tril and triu functions in PyTorch. please look at them as they are straightforward.</li><li>Register buffer is the process of creating temperory parameters that doesnt require gradient tracking. They give nice functionality of moving between CPU and GPU if we register them with PyTorch provided buffer.</li></ol><pre>class Attention(nn.Module):<br>    ### register your buffer here<br>    IGNORE: Float[Tensor, &#39;&#39;]<br>    def __init__(self, cfg: Config):<br>        super().__init__()<br>        self.cfg = cfg<br>        self.W_Q = nn.Parameter(t.empty((cfg.n_heads, cfg.d_model, cfg.d_head)))<br>        self.W_K = nn.Parameter(t.empty((cfg.n_heads, cfg.d_model, cfg.d_head)))<br>        self.W_V = nn.Parameter(t.empty((cfg.n_heads, cfg.d_model, cfg.d_head)))<br>        self.W_O = nn.Parameter(t.empty((cfg.n_heads, cfg.d_head, cfg.d_model)))<br>        self.b_Q = nn.Parameter(t.zeros((cfg.n_heads, cfg.d_head)))<br>        self.b_K = nn.Parameter(t.zeros((cfg.n_heads, cfg.d_head)))<br>        self.b_V = nn.Parameter(t.zeros((cfg.n_heads, cfg.d_head)))<br>        self.b_O = nn.Parameter(t.zeros((cfg.d_model)))<br>        nn.init.normal_(self.W_Q, std=self.cfg.init_range)<br>        nn.init.normal_(self.W_K, std=self.cfg.init_range)<br>        nn.init.normal_(self.W_V, std=self.cfg.init_range)<br>        nn.init.normal_(self.W_O, std=self.cfg.init_range)<br>        self.register_buffer(&#39;IGNORE&#39;, torch.tensor(float(&#39;-inf&#39;), dtype=torch.float32, device = device))  # mention device also<br>    <br>    def forward(self, normalized_resid_pre: Float[Tensor, &#39;batch pos d_model&#39;]) -&gt; Float[Tensor, &#39;batch pos d_model&#39;]:<br>        ### calculate query, key and value vectors and go according to the formula<br>        q = (<br>            einops.einsum(<br>                normalized_resid_pre, self.W_Q, &quot;batch posn d_model, nheads d_model d_head -&gt; batch posn nheads d_head&quot;<br>            )<br>            + self.b_Q<br>        )<br>        k = (<br>            einops.einsum(<br>                normalized_resid_pre, self.W_K, &quot;batch posn d_model, nheads d_model d_head -&gt; batch posn nheads d_head&quot;<br>            )<br>            + self.b_K<br>        )<br>        v = (<br>            einops.einsum(<br>                normalized_resid_pre, self.W_V, &quot;batch posn d_model, nheads d_model d_head -&gt; batch posn nheads d_head&quot;<br>            )<br>            + self.b_V<br>        )<br>        attn_scores = einops.einsum(<br>            q, k, &quot;batch posn_Q nheads d_head, batch posn_K nheads d_head -&gt; batch nheads posn_Q posn_K&quot;<br>            )<br>        attn_scores_masked = self.apply_causal_mask(attn_scores / self.cfg.d_head**0.5)<br>        attn_pattern = attn_scores_masked.softmax(-1)<br><br>        # Take weighted sum of value vectors, according to attention probabilities<br>        z = einops.einsum(<br>            v, attn_pattern, &quot;batch posn_K nheads d_head, batch nheads posn_Q posn_K -&gt; batch posn_Q nheads d_head&quot;<br>        )<br><br>        # Calculate output (by applying matrix W_O and summing over heads, then adding bias b_O)<br>        attn_out = (<br>            einops.einsum(z, self.W_O, &quot;batch posn_Q nheads d_head, nheads d_head d_model -&gt; batch posn_Q d_model&quot;)<br>            + self.b_O<br>        )<br><br>        return attn_out<br><br>    def apply_causal_mask(<br>        self, attn_scores: Float[Tensor, &quot;batch n_heads query_pos key_pos&quot;]<br>    ) -&gt; Float[Tensor, &quot;batch n_heads query_pos key_pos&quot;]:<br>        &quot;&quot;&quot;<br>        Applies a causal mask to attention scores, and returns masked scores.<br>        &quot;&quot;&quot;<br>        # Define a mask that is True for all positions we want to set probabilities to zero for<br>        all_ones = t.ones(attn_scores.size(-2), attn_scores.size(-1), device=attn_scores.device)<br>        mask = t.triu(all_ones, diagonal=1).bool()<br>        # Apply the mask to attention scores, then return the masked scores<br>        attn_scores.masked_fill_(mask, self.IGNORE)<br>        return attn_scores</pre><blockquote><strong><em>Imp takeaway</em></strong></blockquote><p>What information we copy depends on the source token’s residual stream, but this doesn’t mean it only depends on the value of that token, because the residual stream can store more information than just the token identity (the purpose of the attention heads is to move information between vectors at different positions in the residual stream).What does that mean ? <br><strong>Messi is the greatest of all time<br></strong>So when greatest is referring/Attending back to Messi, it doesn’t just see the value <strong>Messi</strong>. Residual stream stores much more than just the identity. It refers to things like<br><strong>Messi</strong> is a subject.<br><strong>Messi</strong> is a person etc.,</p><p>All of this is stored in the residual stream.</p><p>Now Input goes into MLP.</p><h3>Multi — layer Perceptron (MLP Layer)</h3><p>This is very important layer. 2/3rds of Model’s parameters are MLPs. These are responsible for Non — Linear Transformation of given Input vectors.<br>The main Intuition of this layer is to form rich projections. To store facts.</p><p>There is a very Intuitive video made by 3 blue 1 brown about this. It’s a must watch. <a href="https://www.youtube.com/watch?v=9-Jl0dxWQs8&amp;t=498s">https://www.youtube.com/watch?v=9-Jl0dxWQs8&amp;t=498s</a></p><h4>Intuition</h4><p>You can <strong>loosely</strong> think of the MLP as working like a <strong>Key → Value function</strong>, where:</p><p><strong>Input = “Key” (what token currently holds in residual stream)<br>Output = “Value” (what features we want to add to the residual stream)</strong></p><p><strong>For Example Key</strong> = token’s current context vector coming from the residual stream. It Represents the <em>meaning</em> of the token so far (including attention context)<br> Value = non-linear mix of learned features<br><strong>Could be:<br></strong>1. “This is a named entity”<br>2. “This clause is negated”<br>3. “A question is being asked”<br>4. “Boost strength-related features”<br>5. “Trigger next layer’s copy circuit”</p><p>So the MLP says:</p><p>“Oh you’re a <em>token that’s the subject of a sentence AND you were just negated</em>? Cool. Let me output features relevant to <strong>that situation</strong>.” Hope you got the intuition.</p><p>The first hidden layer has 3072 neurons. we call this as <strong>d_mlp</strong> and have declared it in our config. Also the 2nd hidden layer projects these back to d_model space. These have been shown as <strong>W_in and W_out</strong> in the code.<br>We use GeLU Non linearity.</p><pre>class MLP(nn.Module):<br>    def __init__(self, cfg: Config):<br>        super().__init__()<br>        self.cfg = cfg<br>        self.W_in = nn.Parameter(t.empty(cfg.d_model, cfg.d_mlp))<br>        self.b_in = nn.Parameter(t.zeros(cfg.d_mlp))<br>        self.W_out = nn.Parameter(t.empty(cfg.d_mlp, cfg.d_model))<br>        self.b_out = nn.Parameter(t.zeros(cfg.d_model))<br>        nn.init.normal_(self.W_in, std=self.cfg.init_range)<br>        nn.init.normal_(self.W_out, std=self.cfg.init_range)<br><br>    def forward(self, normalized_resid_mid: Float[Tensor, &#39;batch posn d_model&#39;]):<br><br>        ## Its going to do per token level matmul<br>        pre = einops.einsum(normalized_resid_mid, self.W_in, &#39;batch posn d_model,d_model d_mlp-&gt;batch posn d_mlp&#39;) + self.b_in<br>        post = gelu_new(pre)<br>        mlp_out = einops.einsum(pre, self.W_out, &#39;batch posn d_mlp, d_mlp d_model-&gt;batch posn d_model&#39;) + self.b_out<br>        return mlp_out<br><br>    </pre><blockquote>With this, we completed one layer of what we call Transformer Block. There are 12 such layers in GPT-2. Also there are 12 attention heads in GPT that we are implementing. Therefore <strong>n_heads</strong> = 12 and <strong>n_layers</strong> = 12. These have already been coded in the config. Our GPT model contains (<strong>d_model</strong>) 768 dimensions and a vocabulary(<strong>d_vocab</strong>) of over 50257 tokens.</blockquote><p>So this Transformer block is repeated 12 times. Code for TransformerBlock is just connecting ( LayerNorm + Attention + MLP &amp; Skip Connections).</p><pre>class TransformerBlock(nn.Module):<br>    def __init__(self, cfg: Config):<br>        super().__init__()<br>        self.cfg = cfg<br>        self.ln1 = LayerNorm(cfg)<br>        self.attn = Attention(cfg)<br>        self.ln2 = LayerNorm(cfg)<br>        self.mlp = MLP(cfg)<br><br>    def forward(self, resid_pre: Float[Tensor, &#39;batch posn d_model&#39;]) -&gt; Float[Tensor, &#39;batch posn d_model&#39;]:<br>        resid_mid = self.attn(self.ln1(resid_pre)) + resid_pre  ### skip connection<br>        resid_post = self.mlp(self.ln2(resid_mid)) + resid_mid<br>        return resid_post</pre><p>Here skip connections are nothing but adding input directly into the Residual Stream along with Attention and MLP. resid_pre says the residual before normalization, which is raw input. resid mid is the residual after attention and it again gets added. This is done inorder to stabilize training for large amount of time.</p><h3>UnEmbed</h3><p>UnEmbed Matrix is when you want to map the learned representations back to the probability over all the tokens in vocab.</p><p><strong>Questions to Ask:</strong></p><p>Q. What input does it take? <br>A. Residual Stream token vector. [batch posn d_model]</p><p>Q. What does it give out?<br>A. It gives out probability of tokens that are likely given current token. i.e.,<br>a matrix of size [batch posn d_vocab]</p><p>look at logits for how precisely it is calculated.</p><pre>class UnEmbed(nn.Module):<br>    def __init__(self,cfg:Config):<br>        super().__init__()<br>        self.cfg = cfg<br>        self.W_U = nn.Parameter(t.empty(cfg.d_model, cfg.d_vocab))<br>        nn.init.normal_(self.W_U, std=self.cfg.init_range)<br>        self.b_U = nn.Parameter(t.zeros((cfg.d_vocab), requires_grad=False))<br>    def forward(self, normalized_resid_final: Float[Tensor, &#39;batch posn d_model&#39;]) -&gt; Float[Tensor, &#39;batch pos d_vocab&#39;]:<br>        logits = einops.einsum(normalized_resid_final, self.W_U, &#39;batch posn d_model, d_model d_vocab -&gt; batch posn d_vocab&#39;) + self.b_U<br>        return logits</pre><h3><strong>Transformer</strong></h3><p>Finally we arrive at the last part. Here, we just need to put all the components we have seen together. Let’s do that !!!</p><pre>class Transformer(nn.Module):<br>    def __init__(self, cfg: Config):<br>        super().__init__()<br>        self.cfg = cfg<br>        self.embed = Embed(cfg)<br>        self.posembed = PosEmbed(cfg)<br>        self.blocks = nn.ModuleList([TransformerBlock(cfg) for _ in range(cfg.n_layers)])           <br>        self.ln_final = LayerNorm(cfg)<br>        self.unembed = UnEmbed(cfg)<br><br>    def forward(self, tokens: Int[Tensor, &#39;posn&#39;]) -&gt; Float[Tensor, &#39;batch posn d_vocab&#39;]:<br>        residual = self.embed(tokens) + self.posembed(tokens)<br>        for block in self.blocks:<br>            residual = block(residual)<br>        logits = self.unembed(self.ln_final(residual))<br>        return logits</pre><p>Here we go from taking tokens as input to calling residual/transformer blocks for 12 times.</p><p><strong>Implementation detail: </strong>Since all the Transformer blocks have their own parameters to be tracked, we need to define them in ModuleList. This is proper way of Initializing a list of blocks we need.Each block will take input from Residual Stream, will learn and contribute their learnings to Residual Stream.</p><p>Thats it Guys!!!!! Hope you have gained a ton of Knowledge on how to build your own GPT. Support and Follow me for more cool blogs!</p><p>Thanks to Neel Nanda and Callum McDougall !!!! I have learnt a lot from their Materials and Videos. This blog is inspired from their work.</p><p>Connect with Me on: <a href="https://www.linkedin.com/in/akhilshekkari/">https://www.linkedin.com/in/akhilshekkari/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87b12ee0ec3d" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/building-gpt-from-first-principles-code-and-intuition-87b12ee0ec3d">Building GPT From First Principles: Code and Intuition</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Quantization to Inference: Beginners guide for Practical Fine-tuning]]></title>
            <link>https://pub.towardsai.net/from-quantization-to-inference-beginners-guide-for-practical-fine-tuning-52c7c3512ef6?source=rss-d6ae1b1ec945------2</link>
            <guid isPermaLink="false">https://medium.com/p/52c7c3512ef6</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[model-quantization]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[finetune-llm]]></category>
            <dc:creator><![CDATA[Akhil Shekkari]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 00:39:10 GMT</pubDate>
            <atom:updated>2025-04-08T11:59:40.718Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>From Quantization to Inference: </strong>Beginners guide for Practical Fine-tuning — (QLoRA with Mistral 7B)</h3><p>Hi, If you are a beginner and looking for a detailed fine-tuning tutorial, you are in the right place. I will try to explain concept and give you code part.</p><p>Go through my previous blogs if you want a refresher in:</p><ol><li>Quantization(Math details and intuition): <a href="https://shekkari1999.github.io/blog/Memory-optimization.html">Link</a></li><li>LoRA(Theory and Intuition): <a href="https://shekkari1999.github.io/blog/fine-tuning-methods.html">Link</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DL0VgYVTtZgcaaoa" /><figcaption>Finetuning</figcaption></figure><p><strong>Contents:</strong></p><p>1. <a href="#5db3">Setting up colab notebook</a><br>2. <a href="#6899">Checking if model is indeed loaded in 4bit</a><br>3. <a href="#c4f3">Playing with tokenizer and understanding outputs</a><br>4. <a href="#5165">Checking model ouput before fine-tuning</a><br>5. <a href="#790c">Loading and Inspecting dataset for fine-tuning</a><br>6.<a href="#d357"> Formatting dataset to make it ready for fine-tuning</a><br>7. <a href="#3033">Setting up LoRA Adapters</a><br>8. <a href="#8347">Model Training</a><br>9.<a href="#b1ff">Model Inference</a></p><h3>1. Setting up colab notebook</h3><p>I would always suggest getting started in colab instead of local environment. This will save you lot of time and you can focus and experiment faster on actual finetuning part. With that being said, install the below dependencies.</p><pre>## Install bitsandbytes if not already installed.<br>!pip install bitsandbytes<br>!pip install datasets<br>!pip install huggingface_hub </pre><p>For this tutorial, we are going to use Mistral-7b. You need to accept licence to use this model. you can do that by logging into your hugging face account. Accept it here <a href="https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Fmistralai%2FMistral-7B-v0.1">https://huggingface.co/mistralai/Mistral-7B-v0.1</a></p><p>Lets start with few Imports:</p><pre>import torch<br>from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig</pre><h4>Basic Info regarding Imports</h4><ol><li><strong>AutoTokenizer</strong> is used to convert text to corresponding Ids.</li><li><strong>CausalLM</strong> : These language Models predict next word based on previous tokens.<strong>AutoModelForCausalLM</strong> contains all autoregressive Causal Models like chatGPT, Llama etc.,</li><li><strong>BitsAndBytesConfig</strong> is used for specifying how we want to load the model and how do we like to do computation. Useful when we have GPU.</li></ol><pre># loading model in 4bits<br><br>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit = True, <br>    bnb_4bit_quant_type = &#39;nf4&#39;, ## This is instead of having uniform bucket, it will be in Gaussian distribution which is more around zero<br>    bnb_4bit_use_double_quant = True,<br>    bnb_4bit_compute_dtype = torch.float16 <br>)</pre><p>Let’s understand what those parameters mean.</p><ol><li><strong>load_in_4bit</strong>: Loads the mistral modal with its quantized 4bit weights.</li><li><strong>bnb_4bit_quant_type</strong>: Most popular values for this are<br> a. <strong>‘Nf4’</strong> → NormalFloat<br> b. <strong>‘FP4’ → </strong>Float</li></ol><p>In Nf4 the values are more tighter around center. It follows normal distribution, where as in FP4 it is uniform throughout.</p><blockquote>For Example: Around center we find +0.01, +0.02, -0.01, -0.02 and at the extremes we have 3.1, 3.5, -4.1, -4.5 etc.,</blockquote><p>3. <strong>bnb_4bit_use_double_quant : </strong>If you have gone through my first blog, you will find something called scaling factor. This is used in Quantization — DeQuantization. So, if this parameter is set to true, these scaling factors for each quantized block are also quantized. This helps in great memory footprint reduction.</p><p>4. <strong>bnb_4bit_compute_dtype: </strong>This parameter helps decide what should be precision while<strong> </strong>Training/Inference.</p><p>Remember:<br> → Weights are quantized to 4-bit (super compact)<br> → But computation still happens in <strong>higher precision</strong> (to avoid losing accuracy)</p><p>Once this is done, we will just load model according to this configuration by running below code block.</p><pre>model_id = &#39;mistralai/Mistral-7B-v0.1&#39;<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_id, ## load this model<br>    quantization_config=bnb_config, ## load the model like this<br>    device_map=&quot;auto&quot;<br>)</pre><p>All the arguments are self explanatory. The device map refers to the availability of having GPU (moves to CUDA if yes./moves to MPS if apple silicon)</p><h3>2. Checking if model is indeed loaded in 4bit</h3><pre>for name, module in model.named_modules():<br>    if &quot;Linear&quot; in str(type(module)) or &quot;4bit&quot; in str(type(module)):<br>        print(f&quot;{name} -&gt; {type(module)}&quot;)</pre><p>Now, what does that above chunk of code mean ?</p><p>we will be using <strong>named_modules()</strong> in various cases.</p><p><strong>For Example:</strong></p><p>1. Inspecting Model Structure<br>2. Checking layer types<br>3. Applying LoRA<br>4. Replacing Layers<br>5. Adding hooks for visualization, logging, activation tracking<br>6. Freezing specific layers.</p><p><strong>Note:</strong> There is also one more function called <strong>named_parameters()</strong> which would give weights and biases.</p><p>Upon running the above block of code we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2Nt8iCNUCLeoI9ujXAFMQ.png" /><figcaption>bitsandbytes confirmation</figcaption></figure><p>Now we know that we loaded Quantized Model.</p><p>Up Next, we load tokenizer.</p><pre>## Now we need to to tokenizer setup<br><br>tokenizer = AutoTokenizer.from_pretrained(model_id)<br>tokenizer.pad_token = tokenizer.eos_token</pre><p>Every model has got some kind of tokenizer( which converts text to numbers).</p><h3>3. Playing with tokenizer outputs</h3><pre>sentence = &quot; Quantization reduces model size and speeds up inference&quot;<br><br>tokens = tokenizer(sentence)<br>#print(tokens)<br>print(f&quot;Input IDs: {tokens[&#39;input_ids&#39;]}&quot;)<br>print(f&quot;tokens: {tokenizer.convert_ids_to_tokens(tokens[&#39;input_ids&#39;])}&quot;)<br><br># decode back to see what original tokens were<br><br>decoded = tokenizer.decode(tokens[&#39;input_ids&#39;])<br>print(f&#39;decoded text: {decoded}&#39;)</pre><p>We get the below output upon running the above code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s97Cw1oE7HpwC2LeBEGxIw.png" /><figcaption>output</figcaption></figure><ol><li>&lt;S&gt; is the start token. Remaining numbers are different token numbers for different words/tokens.</li></ol><p>2. tokenizer.decode() helps us constructing original sentence.</p><p>Let’s see an example of how batching looks like.</p><pre>sentences = [&#39;Quantization is great&#39;, <br>&#39;LoRA is much more better than Full Finetuning&#39;]<br>batch = tokenizer(<br>    sentences, <br>    padding = True,<br>    truncation = True,<br>    return_tensors = &#39;pt&#39;<br><br>)<br>print(f&#39;Input IDs: {batch[&quot;input_ids&quot;]}&#39;)<br>print(&#39;Tokens: &#39;)<br>for ids in batch[&#39;input_ids&#39;]:<br>    print(tokenizer.convert_ids_to_tokens(ids))</pre><p>lets observe the below output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zr17JAf1YPTFcQQorsiblA.png" /><figcaption>output</figcaption></figure><p>1. Here we process two sentences at once. Hence padding.<br>2. &lt;/s&gt; is padding token which is denoted by “2”.<br>3. Truncate helps in cutting off sentence generation till the max limit mentioned.<br>4. return tensors = ‘pt’ just returns output in Pyorch tensors for further calculations</p><h3><strong>4. Checking model ouput before fine-tuning.</strong></h3><p>Whole purpose of this blog is about finetuning. Before doing that, lets check the model output.</p><pre>prompt_1 = &quot;&quot;&quot;### Instruction:<br>How to cook pasta.<br><br>### Response:&quot;&quot;&quot;<br><br>prompt_2 = &quot;&quot;&quot;### Instruction:<br>How to win chess championship.<br><br>### Response:&quot;&quot;&quot;<br><br>prompt = [prompt_1, prompt_2]<br>inputs = tokenizer(prompt,padding = True, truncation = True,  return_tensors=&quot;pt&quot;).to(model.device)<br><br>with torch.no_grad():<br>    outputs = model.generate(<br>        **inputs,<br>        max_new_tokens=100,<br>        do_sample=True, #### does random sampling instead of greedy search # can do beam search<br>        temperature=0.7,<br>        top_p=0.95<br>    )<br><br># Strip prompt if you just want the model&#39;s generated part<br>for i, output in enumerate(outputs):<br>    response = tokenizer.decode(output, skip_special_tokens=True) #### removes &lt;s&gt;, &lt;PAD&gt; etc.,<br>    completion = response[len(prompt[i]):].strip() ### removes prompt from <br>    print(f&quot;\n Prompt {i+1} Response:&quot;)<br>    print(completion)</pre><p>Nothing new in the code here. we are checking outputs for 2 different prompts.</p><p>torch.no_grad() disables gradient tracking while inference which should be done. After that we are just printing outputs. The output looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lr5xKkYCAC8qOkIz4mMSiA.png" /><figcaption>output response of prompts</figcaption></figure><p>It is not giving steps. It is generating some kind of html and git/file instructions. Good enough reason for us to finetune.</p><h3>5. Loading and Inspecting dataset for fine-tuning.</h3><p>Okay. we are getting there slowly but step by step. Please see dataset format here <a href="https://huggingface.co/datasets/tatsu-lab/alpaca">https://huggingface.co/datasets/tatsu-lab/alpaca</a></p><pre>from datasets import load_dataset<br><br># load a small subset to test quickly <br><br>dataset = load_dataset(&quot;tatsu-lab/alpaca&quot;, split=&quot;train[:1%]&quot;) <br>print(dataset[0][&#39;output&#39;]) ### Accessing output only</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x071EMVZcToc2eUZRW2U8Q.png" /><figcaption>output</figcaption></figure><p>Here outputs are nicely ordered step by step without any html. we are taking only 1% of the data which is enough for practice purposes.</p><p>But We need to format the above dataset. Because there are multiple fields like instruction, input and output in the dataset. Out model understands only one prompt as a continuous string and it gives one response as output.</p><h3>6. Formatting dataset to make it ready for fine-tuning</h3><pre>def format_alpaca(example):<br>    if example[&quot;input&quot;]:<br>        prompt = f&quot;&quot;&quot;### Instruction:\n{example[&#39;instruction&#39;]}\n\n### Input:\n{example[&#39;input&#39;]}\n\n### Response:\n{example[&#39;output&#39;]}&quot;&quot;&quot;<br>    else:<br>        prompt = f&quot;&quot;&quot;### Instruction:\n{example[&#39;instruction&#39;]}\n\n### Response:\n{example[&#39;output&#39;]}&quot;&quot;&quot;<br>    return {&quot;text&quot;: prompt}<br><br># Apply formatting<br>dataset = dataset.map(format_alpaca)<br>dataset[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_Hq3MRub2WL78voDgD9KQ.png" /><figcaption>After formatting</figcaption></figure><p>We can clearly see that, after formatting we have text and response variables in the dataset. They will be used for fine-tuning purposes. we do this to tell the model that as soon as it sees:</p><p><strong>####Instruction → </strong>listen for task<strong><br>####Response</strong> → Generate meaningful response</p><p>Now the next obvious step would be to tokenize these text variable in the dataset. Run below code.</p><pre>def tokenize(example):<br>    return tokenizer(<br>        example[&#39;text&#39;],<br>        truncation = True,<br>        padding = &#39;max_length&#39;,<br>        max_length = 128<br>    )<br><br>tokenized_dataset = dataset.map(tokenize, batched = True)<br><br>print(tokenized_dataset[0][&quot;input_ids&quot;][:10])<br>print(tokenizer.decode(tokenized_dataset[0][&quot;input_ids&quot;]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FE95XLMz2xYHXaw7OyJRbA.png" /><figcaption>output after running above code</figcaption></figure><p>I have cutdown the input_ids[:10] to ten. to see the full ids remove slicing.</p><h3>7. Setting up LoRA Adapters</h3><pre>from peft import LoraConfig, get_peft_model, TaskType<br><br>lora_config = LoraConfig(<br>    r = 32,  #### reducing rank will give you less parameters<br>    lora_alpha = 16, <br>    target_modules = [&#39;q_proj&#39;, &#39;v_proj&#39;],<br>    lora_dropout = 0.1,<br>    bias = &#39;none&#39;,<br>    task_type = TaskType.CAUSAL_LM<br>)<br>model = get_peft_model(model, lora_config)<br>model.print_trainable_parameters()</pre><p>We just define rank, and other useful parameters. Please refer my blog linked at the start to understand theory and intuition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reu92YWxnV6rQRAVegqpHg.png" /><figcaption>output</figcaption></figure><p>We see that we train only 0.18 % parameters(LoRA parameters. Original weights are frozen). This significantly reduces memory footprint and speeds-up training.</p><h3>8. Model Training</h3><pre>from transformers import TrainingArguments, Trainer, DataCollatorForLanguageModeling<br><br>training_args = TrainingArguments(<br>    output_dir=&quot;./qlora-mistral-checkpoint&quot;,       # Folder to save checkpoints and logs<br>    per_device_train_batch_size=4,                 # Batch size per GPU/core<br>    gradient_accumulation_steps=4,                 # Accumulate gradients over 4 steps → simulates batch_size = 4 x 4 = 16<br>    num_train_epochs=1,                            # Train for 1 epoch over the dataset<br>    learning_rate=2e-4,                            # Learning rate (typically 1e-4 to 2e-4 for LoRA)<br>    fp16=True,                                     # Use mixed precision (float16) for faster training and lower memory<br>    logging_steps=10,                              # Log loss every 10 steps<br>    save_steps=50,                                 # Save checkpoint every 50 steps<br>    save_total_limit=1,                            # Keep only the most recent checkpoint (free up disk space)<br>    report_to=&quot;none&quot;                               # Disable logging to W&amp;B, TensorBoard, etc. (can set to &quot;wandb&quot; if needed)<br>)<br><br>trainer = Trainer(<br>    model=model,                                   # The full model with LoRA adapters applied<br>    args=training_args,                            # Training configuration defined above<br>    train_dataset=tokenized_dataset,               # Tokenized dataset with input_ids, attention_mask<br>    tokenizer=tokenizer,                           # Tokenizer for saving and syncing with model<br>    data_collator=DataCollatorForLanguageModeling( # Prepares batches with correct padding/masking<br>        tokenizer, mlm=False                       # mlm=False = causal LM task (not BERT-style masking)<br>    )<br>)<br>trainer.train()</pre><p>I tried to mention comments for all the parameters that we are using. I felt it was sufficient as it is vert simple. However, let me explain what gradient accumulation does here. Model only updates weights <strong>once every 4 steps</strong>, after seeing a total batch of 4 x 4 = 16 samples. This way, it is memory efficient and can train even on small GPU.</p><p><strong>DataCollatorForLanguageModeling:</strong></p><ol><li>This is very important because it handles multiple things. Earlier in the blog, we have seen padding, masking. <strong>DataCollator </strong>handles this job for us. If we don’t use it model starts attending to padded tokens also(which are garbage). This is attention masking.</li><li>MLM masking randomly hides some input tokens and asks model to predict the next one. since we are not doing BERT style model, we opt it as False.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EaHt3f7KeBNPEh533CWoow.png" /><figcaption>output of training</figcaption></figure><p>Training one epoch also gave a noticeable result. Let’s see how to do Inference.</p><h3>9.Model Inference</h3><p>Save the model first.</p><pre>model.save_pretrained(&quot;qlora-mistral-lora&quot;)<br>tokenizer.save_pretrained(&quot;qlora-mistral-lora&quot;)</pre><p>Now load the base-model + QLoRA(saved model)</p><pre>base_model = AutoModelForCausalLM.from_pretrained(<br>    &quot;mistralai/Mistral-7B-v0.1&quot;,<br>    quantization_config=bnb_config,<br>    device_map=&quot;auto&quot;<br>)<br><br># Load LoRA adapters<br>model = PeftModel.from_pretrained(base_model, &quot;qlora-mistral-lora&quot;)<br>tokenizer = AutoTokenizer.from_pretrained(&quot;qlora-mistral-lora&quot;)<br>tokenizer.pad_token = tokenizer.eos_token</pre><p>Finally, we have reached the fun part. Let’s check the output on the same prompts.</p><pre>prompt = &quot;&quot;&quot;### Instruction:<br>How to become chess champion<br>### Response:&quot;&quot;&quot;<br><br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(model.device)<br><br>with torch.no_grad():<br>    outputs = model.generate(<br>        **inputs,<br>        max_new_tokens=100,<br>        do_sample=True, # instead of greedy sampling<br>        temperature=0.7, <br>        top_p=0.9<br>    )<br><br>output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>print(&quot; Model Output:\n&quot;, output_text[len(prompt):].strip())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8EONoamwv8VaLxohYaVhA.png" /><figcaption>Final output image</figcaption></figure><p>Here, we see the output is much more organized, readable and relevant. Hope you have enjoyed the blog and learned something. Let me know in comments if you have any questions.</p><p>If you found this blog helpful , please clap, share, subscribe and stay tuned for the next one.</p><p>My Linkedin: <a href="https://www.linkedin.com/in/akhilshekkari/">https://www.linkedin.com/in/akhilshekkari/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52c7c3512ef6" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/from-quantization-to-inference-beginners-guide-for-practical-fine-tuning-52c7c3512ef6">From Quantization to Inference: Beginners guide for Practical Fine-tuning</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Quantization in Deep Learning]]></title>
            <link>https://medium.com/@akhil.masters21/understanding-quantization-in-deep-learning-771eb9bd7e39?source=rss-d6ae1b1ec945------2</link>
            <guid isPermaLink="false">https://medium.com/p/771eb9bd7e39</guid>
            <dc:creator><![CDATA[Akhil Shekkari]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 06:05:14 GMT</pubDate>
            <atom:updated>2025-03-13T06:05:14.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXcLugv49OZvsA6TQd274A.png" /></figure><p>I break down:</p><p>• Memory footprint optimization</p><p>• Gradient checkpointing</p><p>• Quantization techniques</p><p>• QAT implementation</p><p>Read the full article at</p><p><a href="https://shekkari1999.github.io/blog/Memory-optimization.html">https://shekkari1999.github.io/blog/Memory-optimization.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=771eb9bd7e39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are you an Outlier ?]]></title>
            <link>https://medium.com/@akhil.masters21/are-you-an-outlier-7a6bd807eea8?source=rss-d6ae1b1ec945------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a6bd807eea8</guid>
            <category><![CDATA[z-score]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[normal-distribution]]></category>
            <category><![CDATA[outlier-detection]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Akhil Shekkari]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 06:05:39 GMT</pubDate>
            <atom:updated>2024-11-09T06:05:39.646Z</atom:updated>
            <content:encoded><![CDATA[<h3>Are you an Outlier ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*Yp-tH0Ad6_Q4p9dR.jpg" /></figure><p>Okay. This is easy guys. let&#39;s keep it simple. Use this blog as a guide for handling outliers.</p><p>There are 2 methods widely used to identify outliers.</p><ol><li>Z — score</li><li>IQR method</li></ol><p>To use Z — score, we need one prerequisite…………..</p><p>The data should come from a normal distribution. And why is that ?? Its because…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*uZxenb111lQnbVio.jpg" /></figure><p>Around 68% of the data can be seen with in 1 standard deviation (+1 , -1), around 95% of data can be seen with in 2 standard deviation(+2, -2) and 99.7% of data is within 3 standard deviation(+3, -3).</p><p>So, we can safely remove that 0.3% data which is greater than 3 standard deviations away.</p><p>If data is skewed or is in any other distribution, those properties won’t hold true. But worry not !!!!! we have other methods suitable for this.</p><p><strong>IQR Method:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/0*Rq-2dg7GOZAwFfYP.png" /></figure><p>So, here the idea is simple.</p><ol><li>We compute 25th (<strong><em>Q1</em></strong>)<strong> </strong>and 75th percentile (<strong><em>Q3</em></strong>) values of the data. By the way this is called Interquartile range (Q3 — Q1) . simply put, the values or data points in this region are good.</li><li>Then we define lower bound and upper bound (fence). Now the formula for this is derived based on experiments conducted on lots of data.</li></ol><blockquote><strong>lower_bound = Q1–1.5 * IQR</strong></blockquote><blockquote><strong>upper_bound = Q3 + 1.5 * IQR</strong></blockquote><p>Now, any value outside these bounds are outliers.</p><p>Lets do some quick code practice. Lets work with raw data. Not the fancy kaggle ones. As I said, I want to keep this simple.</p><pre>import numpy as np<br>import pandas as pd<br># lets generate some data<br>np.random.seed(42)<br>data = {<br>    &#39;feature_1&#39; : np.random.normal(50, 5, 100).tolist() + [120, 130, 240], <br>    &#39;feature_2&#39; : np.random.normal(50, 3, 100).tolist() + [60, 70, 80]<br>}<br>df = pd.DataFrame(data)</pre><p>simple right ??</p><p>All we are doing is generating some normal data and adding outliers to it.</p><p>Lets look at the data frame</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*pKRxnv4rIT4Wp1I6bilvSw.png" /></figure><p>Of course, we will look at the outliers too !!!</p><pre>import matplotlib.pyplot as plt<br>plt.scatter(df[&#39;feature_1&#39;], df[&#39;feature_2&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*_WBbtSqjZuR6Lb8YsDrHCw.png" /></figure><p>Now, we see those outliers, let&#39;s write code to remove them.</p><p>IQR Method :</p><pre># define quantiles<br><br>Q1 = df.quantile(0.25)<br>Q3 = df.quantile(0.75)<br>IQR = Q3 - Q1<br><br># define bounds<br><br>lower_bound = Q1 - 1.5 * IQR<br>upper_bound = Q3 + 1.5 * IQR<br><br># capture outliers<br><br>outliers = ((df &lt; lower_bound) | (df &gt; upper_bound))<br><br># exclude them from data<br>df = df[~outliers.any(axis=1)]<br><br>plt.scatter(df[&#39;feature_1&#39;], df[&#39;feature_2&#39;])<br>plt.xlim(0, 250)  # Set your desired x-axis limits<br>plt.ylim(40, 80)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJEiBn2W60e3lVjSisB6CQ.png" /></figure><p>BOOOM !!!. They are gone.</p><p>Z — score:</p><pre>from scipy import stats<br><br>z_scores = np.abs(stats.zscore(df))<br>threshold_pos = 3<br>threshold_neg = -3<br>outliers = (z_scores &gt; threshold_pos | z_scores &lt; threshold_neg)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJEiBn2W60e3lVjSisB6CQ.png" /></figure><p>AGAIN BOOM !!!</p><p>Hope you enjoyed this. Keep Clapping !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a6bd807eea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embracing the Imbalance (Part — 2)]]></title>
            <link>https://medium.com/@akhil.masters21/embracing-the-imbalance-part-2-8bdd93a210f5?source=rss-d6ae1b1ec945------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bdd93a210f5</guid>
            <category><![CDATA[smote]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <dc:creator><![CDATA[Akhil Shekkari]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 04:28:16 GMT</pubDate>
            <atom:updated>2024-10-07T04:28:16.152Z</atom:updated>
            <content:encoded><![CDATA[<h3>Embracing the Imbalance (Part — 2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mg0EdgIkBlinb557HiadTQ.png" /></figure><h3>A Intuitive Guide of Understanding different Techniques</h3><p><strong>(Part — 2, Code)</strong></p><p>Firstly, I hope you have read Part — 1. If not, give it a quick shot, <a href="https://medium.com/@akhil.masters21/embracing-the-imbalance-04969db08dc3?source=your_stories_page-------------------------------------"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><p>If you already have Idea about various performance metrics, you are good to go. If not, I expect you to know about few performance metrics <a href="https://medium.com/@akhil.masters21/performance-metrics-will-be-updated-4d52ba1b446d?source=your_stories_page-------------------------------------">here</a>.</p><p>Now…, let’s enjoy Part — 2 :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*bjxQcp6Opufk71uKIsl7Hg.png" /></figure><p>The dataset we are going to work with is from Kaggle. It is credit card fraud detection. Please find it <a href="https://www.kaggle.com/datasets/mlg-ulb/creditcardfraud/data">here</a>.</p><blockquote>FIRST THINGS FIRST !!!</blockquote><p>⚠️ <strong>This is not a Pandas, Matplotlib blog. I won’t be going in depth with syntax and usage. we will see how to apply different techniques discussed in Part — 1.</strong></p><p>Having said that, staring at lines of code in a blog can sometimes feel like daunting. It’s honestly like going to party which you weren’t invited.</p><p>So, I’m not going to overwhelm you. I will introduce the required amount of code which you will understand and can get started with. I’ll also show you the outputs that you get once you run that block of code. This will ensure we are going in the right direction.</p><p>The only way you will enjoy the code is by typing it out and executing it. Even though you have snippets here, I highly encourage you to go through my notebook that I will share in the end. It contains explanations as well as some bonus content 😜</p><p><strong>Code sample — 1:</strong></p><p>Here we are going to just load file and plot a graph showing distribution of target label.</p><pre># Import necessary libraries<br>import pandas as pd<br>file_path = &#39;creditcard.csv&#39;<br>df = pd.read_csv(file_path)<br><br># Display class distribution<br>class_counts = df[&#39;Class&#39;].value_counts()<br>print(&quot;Class Distribution:\n&quot;, class_counts)<br><br># Visualize the class distribution<br>import matplotlib.pyplot as plt<br><br>class_counts.plot(kind=&#39;bar&#39;, color=[&#39;skyblue&#39;, &#39;salmon&#39;])<br>ax = class_counts.plot(kind=&#39;bar&#39;, color=[&#39;skyblue&#39;, &#39;salmon&#39;])<br>plt.title(&quot;Class Distribution: Non-Fraud vs Fraud&quot;)<br>plt.xlabel(&quot;Class&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.xticks(ticks=[0, 1], labels=[&#39;Non-Fraud (0)&#39;, &#39;Fraud (1)&#39;])<br><br># Annotate bars with counts<br>for i, count in enumerate(class_counts):<br>    ax.text(i, count + 50, str(count), ha=&#39;center&#39;, va=&#39;bottom&#39;)<br><br>plt.show()</pre><p><strong>Output — 1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awMOVpdPIWQZ2-BN0t0XZw.png" /></figure><p>Alrightttt, we have some serious Imbalance here. Only 492 data points correspond to Fraud Transactions.</p><blockquote>Good for the society, bad for the model to learn 😝</blockquote><p><strong>Code snippet — 2</strong></p><p>Let’s just fit a model and see how this does on test dataset without any techniques. We are using Logistic Regression to solve this classification problem. I chose this model because it explains a lot in terms of feature importance which you will see later.</p><pre># Prepare and split data<br><br>from sklearn.model_selection import train_test_split<br><br># Separate features and target variable<br>X = df.drop([&#39;Class&#39;], axis=1)<br>y = df[&#39;Class&#39;]<br><br># Split into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)<br><br># ------------------------------------------------------------------------------------------------<br># Run the model<br><br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import classification_report<br><br># Train a Logistic Regression model with class weighting<br>model = LogisticRegression(random_state=42)<br>model.fit(X_train, y_train)<br><br># Predict and evaluate<br>y_pred = model.predict(X_test)<br>print(&quot;Classification Report Without Handling Imbalance:\n&quot;, classification_report(y_test, y_pred))</pre><p><strong>Output — 2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*UTAlYXvTSP2ajDO0_zyqDw.png" /></figure><p>Yoo, that’s the worst. Let’s do Interpretation.</p><p>For class — 0(i.e., Non Fraud) Model has scored 100 % in all areas.</p><p>For class — 1,</p><p>Precision is <strong>77%</strong>.</p><blockquote><strong>Out of all the transactions predicted as fraudulent, only 77% were actually fraud.</strong></blockquote><p>Recall is<strong> 63%.</strong></p><blockquote><strong>Out of all the actual fraudulent transactions, the model only caught 63%. This means</strong> <strong>37% of the fraudulent cases were missed.</strong></blockquote><p>F1 — score is <strong>69%.</strong></p><blockquote><strong>F1 — score is the harmonic mean of precision and recall. Its like final report card balancing both and assess how well our model is doing.</strong></blockquote><p>Check out in-depth explanation in Metrics blog.</p><p>Wouldn’t it be great if we can visually see our data points ? The improvements on datapoints our model made ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*ypEqqZyxGIe8B61o8jmAQA.png" /></figure><p>Let’s visualize how our model has done on test — set.</p><p>Code snippet — 3</p><p>🛑 PCA is a Technique to visualize high dimensional data in 2D plane. since we have 29–30 features, (1 feature = 1 dimension), we need to project these higher dimension to 2D plane</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import pandas as pd<br>from sklearn.decomposition import PCA<br><br><br>missed_frauds = X_test[(y_test == 1) &amp; (y_pred == 0)].copy()<br>missed_frauds[&#39;Class&#39;] = &#39;Missed Fraud&#39;  <br><br>correct_frauds = X_test[(y_test == 1) &amp; (y_pred == 1)].copy()<br>correct_frauds[&#39;Class&#39;] = &#39;Correctly Classified Fraud&#39;  <br><br>combined_fraud_df = pd.concat([missed_frauds, correct_frauds])<br><br># Applying PCA to reduce dimensionality<br>pca = PCA(n_components=2, random_state=42)<br>pca_components = pca.fit_transform(combined_fraud_df.drop(columns=[&#39;Class&#39;]))  # Apply PCA on feature columns only<br><br># Creating a new DataFrame to hold PCA components and class labels<br>pca_df = pd.DataFrame(data=pca_components, columns=[&#39;PCA1&#39;, &#39;PCA2&#39;])<br>pca_df[&#39;Class&#39;] = combined_fraud_df[&#39;Class&#39;].values  <br><br>class_counts_before_smote = pca_df[&#39;Class&#39;].value_counts()<br><br><br># code for plotting <br>plt.figure(figsize=(14, 8))<br><br># Scatter plot for the PCA data points<br>plt.subplot(1, 2, 1)  # First subplot for scatter plot<br>sns.scatterplot(data=pca_df, x=&#39;PCA1&#39;, y=&#39;PCA2&#39;, hue=&#39;Class&#39;, palette={&#39;Missed Fraud&#39;: &#39;red&#39;, &#39;Correctly Classified Fraud&#39;: &#39;green&#39;}, alpha=0.7)<br>plt.title(&quot;PCA Visualization of Missed vs Correctly Classified Fraudulent Transactions (Before SMOTE)&quot;)<br>plt.xlabel(&quot;PCA Component 1&quot;)<br>plt.ylabel(&quot;PCA Component 2&quot;)<br>plt.legend(title=&quot;Class&quot;)<br><br># Count plot for showing count of each class<br>plt.subplot(1, 2, 2)  # Second subplot for count plot<br>sns.countplot(data=pca_df, x=&#39;Class&#39;, palette={&#39;Missed Fraud&#39;: &#39;red&#39;, &#39;Correctly Classified Fraud&#39;: &#39;green&#39;})<br>plt.title(&quot;Count of Missed vs Correctly Classified Fraudulent Transactions (Before SMOTE)&quot;)<br>plt.xlabel(&quot;Class&quot;)<br>plt.ylabel(&quot;Count&quot;)<br><br># Annotate counts on the bars<br>for p in plt.gca().patches:<br>    height = p.get_height()<br>    plt.gca().text(p.get_x() + p.get_width() / 2., height + 1, str(int(height)), ha=&#39;center&#39;, va=&#39;bottom&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><p><strong>Output — 3</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDS_ub3HwGp3HMNAA7S-Iw.png" /></figure><blockquote>That means, All the 50 red points, the model missed and did not learn. That’s a high number. we need to reduce the number.</blockquote><h3>Now, lets apply SMOTE</h3><p><strong>Code snippet — 4</strong></p><p>imblearn, short for <strong>Imbalanced-Learn</strong>, is a powerful Python library designed specifically to handle <strong>imbalanced datasets. </strong>we import SMOTE from it.</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import pandas as pd<br>from sklearn.decomposition import PCA<br>from imblearn.over_sampling import SMOTE<br><br># Assuming X_train and y_train are your training data before applying SMOTE<br><br># Apply SMOTE to balance the training data<br>smote = SMOTE(random_state=42)<br>X_train_smote, y_train_smote = smote.fit_resample(X_train, y_train)  # Apply SMOTE to the training set<br><br># Create a DataFrame for visualizing the data after SMOTE<br>X_train_smote_df = pd.DataFrame(X_train_smote, columns=X_train.columns)  # Create a DataFrame for SMOTE features<br>X_train_smote_df[&#39;Class&#39;] = y_train_smote  # Add class labels to the DataFrame<br><br># Apply PCA to reduce dimensions to 2 components for visualization after SMOTE<br>pca = PCA(n_components=2, random_state=42)<br>X_train_smote_pca = pca.fit_transform(X_train_smote_df.drop(columns=[&#39;Class&#39;]))  # Apply PCA on feature columns only<br><br># Create a DataFrame for PCA components and class labels<br>pca_smote_df = pd.DataFrame(data=X_train_smote_pca, columns=[&#39;PCA1&#39;, &#39;PCA2&#39;])<br>pca_smote_df[&#39;Class&#39;] = X_train_smote_df[&#39;Class&#39;].map({0: &#39;Non-Fraud&#39;, 1: &#39;Fraud&#39;})  # Map class labels<br><br># Separate correctly classified fraud and missed frauds based on the original predictions<br># Assume `y_test` and `y_pred_smote` are defined, containing the true labels and predictions after applying SMOTE<br><br># Get false negatives (Missed fraudulent transactions after SMOTE)<br>missed_frauds_after_smote = X_test[(y_test == 1) &amp; (y_pred_smote == 0)].copy()<br>missed_frauds_after_smote[&#39;Class&#39;] = &#39;Missed Fraud (After SMOTE)&#39;  # Assign class label &#39;Missed Fraud (After SMOTE)&#39;<br><br># Get correctly classified fraud transactions for comparison after SMOTE<br>correct_frauds_after_smote = X_test[(y_test == 1) &amp; (y_pred_smote == 1)].copy()<br>correct_frauds_after_smote[&#39;Class&#39;] = &#39;Correctly Classified Fraud (After SMOTE)&#39;  # Assign class label &#39;Correctly Classified Fraud (After SMOTE)&#39;<br><br># Combine missed frauds and correctly classified fraud transactions after SMOTE into one DataFrame<br>combined_fraud_df_after_smote = pd.concat([missed_frauds_after_smote, correct_frauds_after_smote])<br><br># Apply PCA to reduce dimensions for the test set after SMOTE<br>X_test_pca_after_smote = pca.transform(combined_fraud_df_after_smote.drop(columns=[&#39;Class&#39;]))  # Apply PCA<br><br># Create a DataFrame for PCA components and class labels after SMOTE<br>pca_test_df_after_smote = pd.DataFrame(data=X_test_pca_after_smote, columns=[&#39;PCA1&#39;, &#39;PCA2&#39;])<br>pca_test_df_after_smote[&#39;Class&#39;] = combined_fraud_df_after_smote[&#39;Class&#39;].values  # Add class labels<br><br># Count of each category (Missed Fraud vs Correctly Classified Fraud) after SMOTE<br>class_counts_after_smote = pca_test_df_after_smote[&#39;Class&#39;].value_counts()<br><br># Create two subplots: scatter plot and count plot<br>plt.figure(figsize=(14, 8))<br><br># Scatter plot for the PCA data points after SMOTE<br>plt.subplot(1, 2, 1)  # First subplot for scatter plot<br>sns.scatterplot(data=pca_test_df_after_smote, x=&#39;PCA1&#39;, y=&#39;PCA2&#39;, hue=&#39;Class&#39;, palette={&#39;Missed Fraud (After SMOTE)&#39;: &#39;red&#39;, &#39;Correctly Classified Fraud (After SMOTE)&#39;: &#39;green&#39;}, alpha=0.7)<br>plt.title(&quot;PCA Visualization of Missed vs Correctly Classified Fraudulent Transactions (After SMOTE)&quot;)<br>plt.xlabel(&quot;PCA Component 1&quot;)<br>plt.ylabel(&quot;PCA Component 2&quot;)<br>plt.legend(title=&quot;Class&quot;)<br><br># Count plot for showing count of each class after SMOTE<br>plt.subplot(1, 2, 2)  # Second subplot for count plot<br>sns.countplot(data=pca_test_df_after_smote, x=&#39;Class&#39;, palette={&#39;Missed Fraud (After SMOTE)&#39;: &#39;red&#39;, &#39;Correctly Classified Fraud (After SMOTE)&#39;: &#39;green&#39;})<br>plt.title(&quot;Count of Missed vs Correctly Classified Fraudulent Transactions (After SMOTE)&quot;)<br>plt.xlabel(&quot;Class&quot;)<br>plt.ylabel(&quot;Count&quot;)<br><br># Annotate counts on the bars<br>for p in plt.gca().patches:<br>    height = p.get_height()<br>    plt.gca().text(p.get_x() + p.get_width() / 2., height + 1, str(int(height)), ha=&#39;center&#39;, va=&#39;bottom&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><p><strong>Output — 4</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0P-MRufvkW4sZWjhWmB7bg.png" /></figure><p>Its already so much better now. Only 12 data points remain. Our Model has learned some valuable info hurray…… 🔥</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*NU-nHgsZKtme8WMat8ylqQ.png" /></figure><p>Yepppp, I know. Let me tell you what changed. So, In the beginning, I have kept a link to the dataset that we were using. If you had opened it, you would have noticed we have around 28–29 features like v1,v2….</p><p>These weights/coefficients of these features contribute to the model’s decision making.I would like to show you the difference between those weights before and after we applied SMOTE.</p><p><strong>Code snippet — 5</strong></p><pre># Get feature importances for Logistic Regression model<br>feature_importances_before = model.coef_[0]  # Coefficients for original model<br>feature_importances_after = model_smote.coef_[0]  # Coefficients for SMOTE model<br><br># Create a DataFrame to compare<br>feature_comparison_df = pd.DataFrame({<br>    &#39;Feature&#39;: X_train.columns,<br>    &#39;Importance Before&#39;: feature_importances_before,<br>    &#39;Importance After&#39;: feature_importances_after<br>})<br><br># Display the comparison<br>print(feature_comparison_df.sort_values(&#39;Importance After&#39;, ascending=False))</pre><p><strong>Output — 5</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*nlKy-qp5dNY1oRXEa_VJOg.png" /></figure><p>So observe, the feature importance for V4 before was around 0.04. You might be wondering what the heckkk is V4 ? Well, we don’t know. Could be anything. Could be the time since last time that user spent huge money, or anything else. Since this is sensitive information, the dataset features are scaled and feature names are named as V1, V2 etc.,</p><p>Anyway, After SMOTE, the model has learned and adjusted its features coefficients which is great. So the model has improved learning on its overall feature set to better make informed decisions, Hurrayy…. 😝</p><h3><strong>Closing Notes</strong></h3><ol><li>You should check out the notebook which would kinda give you more Hands — on and you would be exposed to additional methods and comparisions. (I will release it shortly 😄)</li><li>I have only shown you SMOTE. You can similarly apply ADASYN or Class weighting. You can also try out different model like Random Forest to check if SMOTE or other methods help increase the chosen metric.</li><li>Also, there are still 12 data points which are incorrectly missed. what can you do about it ? Handling Imbalance is one of the area in Data Science. Now you need other areas like Missing values, Handling Outliers etc.,</li></ol><p>Hope you have got a sense of how to apply Techniques to deal with Imbalance. <strong>Please Share and Keep Clapping</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bdd93a210f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Metrics : (Will be Updated)]]></title>
            <link>https://medium.com/@akhil.masters21/performance-metrics-will-be-updated-4d52ba1b446d?source=rss-d6ae1b1ec945------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d52ba1b446d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[performance-metrics]]></category>
            <category><![CDATA[f1-score]]></category>
            <dc:creator><![CDATA[Akhil Shekkari]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 04:17:11 GMT</pubDate>
            <atom:updated>2024-10-07T04:22:58.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>Performance Metrics : (Will be Updated)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNN4YyFqV2GawnVrv8JhIg.png" /></figure><p>(Intuitive Example)</p><p>Imagine you’re a cat trying to catch mice.</p><p><strong>Precision</strong> measures how many of those “mice” you caught were actually mice So, if you caught 10 creatures but only 6 were mice, your Precision is 60%. It’s like saying, “I’m a sniper — I only shoot when I’m sure!” 🎯</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*T-aSFE5GrP43NxhnVHHZHw.png" /></figure><p><strong>Recall</strong>: Now, Recall is like a cat’s determination to catch every mouse in the house. It measures how many of the actual mice you managed to catch. If there were 10 mice running around and you caught 8, your Recall is 80%. Think of Recall as your Sherlock Holmes— did you miss any mice? 🕵️‍♂️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*8CoYm_AMyukQyE_4mg_ZCQ.png" /></figure><p><strong>F1-Score</strong>: This is the cat’s overall mouse-catching performance. It’s the <em>balancing act</em> between being a precise hunter (Precision) and a thorough chaser (Recall). If Precision is about not catching fluff and Recall is about not missing any mice, the F1-Score is your final report card! 📝</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*Ave8C2Uo1pt-CVcmZ2WgLA.png" /></figure><p>It tells you how well you balanced accuracy and completeness in your hunt. High F1-Score = A+ in mouse hunting! 🏅</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d52ba1b446d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embracing the Imbalance]]></title>
            <link>https://medium.com/@akhil.masters21/embracing-the-imbalance-04969db08dc3?source=rss-d6ae1b1ec945------2</link>
            <guid isPermaLink="false">https://medium.com/p/04969db08dc3</guid>
            <category><![CDATA[sampling-methods]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[imbalanced-dataset]]></category>
            <category><![CDATA[smote]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <dc:creator><![CDATA[Akhil Shekkari]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 06:24:52 GMT</pubDate>
            <atom:updated>2024-10-06T06:24:52.635Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*IQq-R5m4VjqlB4Int18LMg.png" /></figure><h3><strong>A Intuitive Guide of Understanding different Techniques</strong></h3><h3><strong>(Part— 1, Theory)</strong></h3><p>Ever caught yourself bragging about a 95% accuracy score, only to realize it’s as pointless as using a semicolon in Python? 😂 That’s imbalanced data for you — making useless things look valuable!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*iA4OaIcQuUUO2YzNnUYl1A.png" /></figure><p>(<strong>Just like your undergrad scores…, ooops sorry geeks !!!</strong>)</p><p>Lets keep this blog light weighted :), we’ll try to understand techniques to handle the Imbalance Intuitively. I will introduce the best practices, guidelines and code in the Next part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*QvX-4WmqPW9AvJ5u4Wz66A.png" /></figure><blockquote>FIRST THINGS FIRST !!!</blockquote><p><strong>What Are Imbalanced Datasets?</strong></p><p>Imbalanced datasets are those where one class has significantly more samples than the others. This Imbalance can make it hard for the model to learn equally from all classes, often leading to biased predictions.</p><p><strong>Why is it a problem?</strong></p><p>Let&#39;s go through an Intuitive example.</p><blockquote>Imagine you are teaching a model to detect fraud, but the dataset has 95% non-fraudulent transactions and only 5% fraudulent ones. The model thinks, “Hey, if I just predict <em>everything</em> as non-fraudulent, I’ll be right 95% of the time!” So, it does exactly that and sits back thinking, “I’m a genius!” Meanwhile, all the actual frauds are getting through, and the model has no idea why it’s performing poorly. 🙃</blockquote><p>So thats why It’s a problem. Your model needs to learn the characteristics of fraudulent transactions. Due to your majority class being Non — Fraudulent, your model learns only those characteristics !!!</p><p>Alright, Now you know why it is a problem. Let&#39;s go through………</p><h4><strong><em>What can you do about it ?</em></strong></h4><ol><li><strong>Oversampling the Minority Class</strong></li></ol><p>Increase the number of samples in the minority class to match the majority class.</p><blockquote>It’s like giving more screen time to a lesser-known actor so they don’t get overshadowed by the superstar!</blockquote><p>This can be done using the following methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*0TzFsxvjDzX7cv3BsFNAPQ.png" /></figure><p><strong>a. Random Oversampling</strong>: Duplicate existing samples from the minority class until the desired class balance is achieved.</p><blockquote>Random oversampling is like <em>copy-pasting</em> the same scenes of that actor multiple times in the movie. Sure, you’ve increased their screen time, but it’s the same old scene over and over again. Viewers might get bored, and the actor’s presence still doesn’t feel as impactful as the superstar. This might lead to “overfitting,” where the audience knows the scene by heart but gains no new insight.</blockquote><p><strong>b. SMOTE (Synthetic Minority Over-sampling Technique)</strong>: Generates synthetic samples for the minority class by interpolating between existing samples.</p><p>Going back to the Fraud — Non Fraud example,</p><blockquote>When you apply <strong>SMOTE</strong>, it looks at the existing fraudulent transactions and creates synthetic data points by combining characteristics of existing fraud cases. For example, if two fraud transactions have a similar pattern but different transaction amounts, SMOTE might generate a new synthetic sample with a transaction amount that’s in between the two. This approach helps in <strong>expanding the fraud transaction space</strong> and gives the model more instances to learn from.</blockquote><p><strong>c. ADASYN (Adaptive Synthetic Sampling)</strong>: A variant of SMOTE that creates more synthetic samples in regions where the minority class is sparsely represented.</p><blockquote>When you apply <strong>ADASYN</strong>, it will identify those sparse regions where the fraud transactions are closely surrounded by non-fraud cases. For instance, if there are a few fraud cases with a high transaction amount that are often mistaken for legitimate transactions, ADASYN will create more synthetic samples near these high transaction fraud cases to give the model more data to learn from.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ef6diivr6N2VCu4RxIdk_Q.png" /><figcaption>(ADASYN)</figcaption></figure><p>Okay, Okayy. I got your pulse, Let me summarize :)</p><blockquote><strong>ADASYN identifies fraud which are close to Non-fraud, whereas SMOTE just takes care of Fraud which might or might not be that close to Non-fraud.</strong></blockquote><p>2. <strong>Undersampling the Majority Class</strong></p><p>Reduce the number of samples in the majority class. This helps the model not to get overwhelmed by the dominant class. But be careful — not to throw away too much valuable data!</p><ul><li><strong>Random Undersampling</strong>: Randomly remove samples from the majority class until a balanced class distribution is achieved.</li></ul><blockquote>Well, this is simple. I think you guys must have figured out so I am not giving an example for this 👊</blockquote><ul><li><strong>Cluster Centroids</strong>: Reduce the majority class by clustering samples and replacing them with their centroids.</li></ul><blockquote>If you have 1,000 fraudulent and 20,000 non-fraudulent transactions, using <strong>Cluster Centroids</strong> will group the 20,000 non-fraudulent transactions into, say, 1,000 clusters. For each cluster, it calculates a centroid (mean point) that represents the “average” transaction for that group. This reduces the majority class to 1,000 representative points, maintaining its overall structure while matching the minority class size. Now, your dataset is balanced with 1,000 fraud and 1,000 centroid-based non-fraud transactions.</blockquote><p>👊 Super man is the centroid :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*datFexddUUxwVPe4UJg2SQ.png" /></figure><p>3. <strong>Class weighting</strong></p><p>I knowww, Just when you thought you are done, the tough guy enters !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*fhBtWFvXbTRRJokEG_XvZA.png" /></figure><p><strong>Why use class weighting ??</strong></p><p>In general, <strong>class weighting</strong> is the most commonly used , especially in scenarios where you don’t want to alter the data distribution.</p><p>Example : Medical Diagnosis.</p><p>You simply should not make up a random data point in the field of Medicine. You can also employ this in detecting fraudulent trasactions if you don’t want to alter the Distribution too much.</p><blockquote>Imagine you’re building a model to detect <strong>rare diseases</strong> in a hospital dataset, where 98% of the patients are healthy and only 2% have a rare disease. When you set class_weight=’balanced’, the model is told that misclassifying a patient with a rare disease is much more serious than misclassifying a healthy patient.</blockquote><p>The model adjusts by giving more attention to detecting the rare disease, even if it means sometimes predicting disease in healthy patients (false positives). Hope that cleared things up!!!</p><p>Alright !!!!! I will be back with a bang in Part — 2.</p><p>See ya !</p><p>Do Clap :) and share</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04969db08dc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>