<?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 Yash Rawal on Medium]]></title>
        <description><![CDATA[Stories by Yash Rawal on Medium]]></description>
        <link>https://medium.com/@yashrawal987?source=rss-e81cc43a5dc2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*F0rfUKQMzgs87dDU</url>
            <title>Stories by Yash Rawal on Medium</title>
            <link>https://medium.com/@yashrawal987?source=rss-e81cc43a5dc2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:19:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yashrawal987/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[FragmentStream Attention: Training a Transformer in Budget]]></title>
            <link>https://medium.com/@yashrawal987/fragmentstream-attention-training-a-transformer-in-budget-f178cbbd5f62?source=rss-e81cc43a5dc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f178cbbd5f62</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Yash Rawal]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 19:57:35 GMT</pubDate>
            <atom:updated>2025-02-10T19:57:35.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q52eeE7YDRFWLtgz-v3xmw.jpeg" /></figure><p>Have you ever wondered how large language models (LLMs) like GPT and Llama actually work? Sure, you can use pre-trained models with just a few lines of code, but the real challenge is understanding what’s happening behind the scenes. I decided to explore — it’s complex and frustrating, but absolutely possible.</p><p>My journey began while working on company project in which I learned to utilize the pretrained Llama 3.1 model and my curiosity begins from there like How is it working?, How is it been developed?, Can I make something like this?</p><p>While learning about it like any genius person, I stumbled upon this famous research paper, ‘<a href="https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf"><strong>Attention is all you need</strong></a><strong>,</strong>’ after reading this and understanding the Transformer Architecture.</p><blockquote><strong>‘I started my own bold Experimentation: a lean, mean 3-million-parameter model, trained for 20 hours on Kaggle’s free P100 GPU. Proof that you don’t need a supercomputer to chase big ideas — just determination, curiosity, and a dash of resourcefulness!’</strong></blockquote><p>I began by developing a simple character-level model that only required 80 characters as tokens and 1,000 lines of dataset. As I improved it, I ended up creating this model using techniques like byte-pair encoding for word and sub word (like suffix and prefix) based tokenization and even stumbled upon some surprising discoveries, which I’ll discuss later in future articles. Around the same time, when I first started learning about Transformers, I was amazed by their power but also frustrated by how much memory they consumed it was like building a sandcastle which is washed away by the waves again and again!</p><p>This frustration led me to explore ways to make Transformers more memory-efficient, eventually leading to the idea of “<strong>FragmentStream Attention”</strong>.</p><p>But before diving into the details, let’s first explore <em>why</em> memory matters.</p><h3><strong>First things first, Why do Transformer need so much memory?</strong></h3><p>Now Transformer is an advanced technique which is dominating the field of <strong>NLP and Language models</strong> because they are able to understand long sequences and recognize patterns in this large text data .</p><p>It’s simple the more context and knowledge base you want to store the more memory you are going to need.</p><p>Now this transformers are very smart they help you with tasks like translating languages, writing stories and maybe articles too. They can do this because they have something called <strong>“attention”</strong> which allow them to read only most important part and that’s why they use lot of memory while training.</p><p><strong>What’s the Problem With Traditional Attention?</strong></p><p>In the traditional Transformers, attention works by comparing <strong>every word to every other word</strong> in a sentence. That means they make a giant grid, like a big table, to keep track of how important each word is compared to all the others. This table grows really, really big if the sentence is too long.</p><p><strong>Why This Is a Problem:</strong></p><ol><li><strong>It uses too much memory:</strong> The grid gets bigger and bigger as the text gets longer. If the text is 1,000 words, the grid is 1,000 x 1,000! That’s HUGE.</li><li><strong>It’s slow:</strong> Transformers have to fill in every box in the grid, which takes a lot of time.</li></ol><p>Let’s look at an example in code:</p><pre># Traditional Attention (simplified)<br>B, T, C = x.shape  # B=batch size, T=sequence length, C=dimensions<br>q = self.query(x)  # (B, T, C)<br>k = self.key(x)    # (B, T, C)<br><br># Store ALL attention scores at once!<br>attention_scores = q @ k.transpose(-2, -1)  # (B, T, T) - This is huge!<br>attention = softmax(attention_scores) @ v    # More memory usage<br># Imagine T is 1,000—that&#39;s 1,000 x 1,000 = 1,000,000 boxes!</pre><p>If you’ve ever tried to carry too many groceries at once, you know how hard it is. That’s what happens to Transformers when the grid is too big they drop everything.</p><h3><strong>FragmentStream Attention: A Smarter and Cost Effective Way to Work</strong></h3><p>Now, let’s talk about how <strong>FragmentStream Attention</strong> fixes this! Now what i did is simply <strong>divided the process into batches.</strong> Instead of looking at the whole book at once, it splits the book into small chunks, or <strong>fragments</strong>, and works on one piece at a time.</p><p>Imagine reading one page of a book, writing down the important stuff, and then moving on to the next page. Once you have read all the pages, you put all the notes together the notes from each page to form a complete understanding of the entire book. This step-by-step approach ensures nothing is overlooked while keeping the process efficient. That’s what FragmentStream Attention does.</p><p><strong>Key Ideas Behind FragmentStream Attention:</strong></p><ol><li><strong>Break the text into pieces:</strong> It divides the text into smaller parts (like 128 words at a time).</li><li><strong>Focus on one part at a time:</strong> It only compares the words within each piece instead of looking at the whole text at once.</li><li><strong>Combine the results:</strong> After working on each part, it adds everything together to get the final answer.</li><li><strong>Keep it organized:</strong> It still remembers the order of the text so everything makes sense.</li></ol><p><strong>This is how it looks like in python code:</strong></p><pre># FragmentStream_Attention implementation (simplified)<br><br>fragment_size = 128  # Process 128 tokens at a time<br>for i in range(0, T, fragment_size):  # Process queries in fragments<br>    q_fragment = q[:, i:i+fragment_size]  # Take small group of queries<br>    for j in range(0, T, fragment_size):  # Process keys/values in fragments<br>        k_fragment = k[:, j:j+fragment_size]  # Take small group of keys<br>        v_fragment = v[:, j:j+fragment_size]  # And corresponding values        <br>        # Compare only these small fragments<br>        scores = q_fragment @ k_fragment.transpose(-2, -1)<br>        # Process and accumulate results</pre><p><strong>And this is how I imagine it works on hardware:</strong></p><pre>[Full Matrix in Memory]      [fragment 1] [Clean Up] [fragment 2] [Clean Up]<br> X X X X X X X X X X     ➜      X X X        ➜         X X X        ➜ <br> X X X X X X X X X X     ➜      X X X        ➜         X X X        ➜ <br> X X X X X X X X X X     ➜      X X X        ➜         X X X        ➜ <br> X X X X X X X X X X     ➜      X X X        ➜         X X X        ➜</pre><p>Yeah! I know It may sound funny but it make significant changes.</p><p><strong>And this is how I utilized this in my model:</strong></p><pre>class FragmentStream_Attention(nn.Module):<br>    &quot;&quot;&quot;<br>      Initialize FragmentStream Attention module<br>      <br>      Args:<br>      - head_size: Dimensionality of attention heads<br>      - block_size: Maximum sequence length<br>      - dropout: Regularization rate<br>      - fragment_size: Size of text fragments to process (default 128 tokens)<br>    &quot;&quot;&quot;<br>    def __init__(self, head_size, block_size, dropout, fragment_size=128):<br>        super().__init__()<br>        self.head_size = head_size<br>        self.fragment_size = fragment_size<br>        self.dropout = nn.Dropout(dropout)<br>        self.register_buffer(&#39;tril&#39;, torch.tril(torch.ones(block_size, block_size)))<br>        <br>    def forward(self, q, k, v):<br>        B, T, C = q.shape<br>        <br>        # Initialize output tensor<br>        out = torch.zeros_like(v)<br>        <br>        # Process attention in fragments to save memory<br>        for i in range(0, T, self.fragment_size):<br>            j_start = i<br>            j_end = min(T, i + self.fragment_size)<br>            <br>            # Current fragment of queries<br>            q_fragment = q[:, i:j_end]<br>            <br>            # Calculate attention scores for this fragment<br>            attn_weights = torch.zeros(B, j_end-i, T, device=q.device)<br>            <br>            for j in range(0, T, self.fragment_size):<br>                k_fragment = k[:, j:min(T, j + self.fragment_size)]<br>                <br>                # Compute attention scores for this block<br>                scores = (q_fragment @ k_fragment.transpose(-2, -1)) * (C ** -0.5)<br>                <br>                # Apply causal mask<br>                scores = scores.masked_fill(<br>                    self.tril[i:j_end, j:min(T, j + self.fragment_size)] == 0, <br>                    float(&#39;-inf&#39;)<br>                )<br>                <br>                attn_weights[:, :, j:min(T, j + self.fragment_size)] = scores<br>            <br>            # Softmax over the entire sequence length<br>            attn_weights = F.softmax(attn_weights, dim=-1)<br>            attn_weights = self.dropout(attn_weights)<br>            <br>            # Compute weighted sum of values in fragments<br>            for j in range(0, T, self.fragment_size):<br>                v_fragment = v[:, j:min(T, j + self.fragment_size)]<br>                out[:, i:j_end] += attn_weights[:, :, j:min(T, j + self.fragment_size)] @ v_fragment<br>                <br>        return out<br></pre><p><strong>How FragmentStream Attention Works Inside</strong></p><p>Let’s look deeper into what happens when FragmentStream Attention reads the text:</p><p><strong>Step-by-Step Explanation:</strong></p><ol><li><strong>Break the text into chunks:</strong> If the text has 1,000 words, and each fragment can hold 128 words, it splits the text into about 8 parts.</li><li><strong>Compare within each fragment:</strong> It looks at the words in each fragment to figure out which ones are important.</li><li><strong>Write down the results:</strong> After working on each fragment, it writes down the important things.</li><li><strong>Put everything together:</strong> At the end, it combines the results from all the fragments to get the full answer.</li></ol><p>By doing this smartly, it saves a TON of memory and works faster. Plus, it works on low or older hardware like NVIDIA’s P100 GPU!</p><p><strong>Here is the Flow Chart of the my model:</strong></p><figure><img alt="FragmentStream_Attention complete implemetation architecture in a Transformer based model" src="https://cdn-images-1.medium.com/max/1024/1*NvuF5Yvsvgdm-hpdl4bfDQ.png" /></figure><p>you can also checkout this experiment on this <strong>Kaggle notebook</strong> and <a href="https://github.com/YashRL/FragmentStream_Attention_llm"><strong>GitHub</strong></a><strong> repository</strong>.</p><h3><strong>Challenges and Lessons Learned</strong></h3><ol><li><strong>Balancing Memory and Accuracy:</strong> Splitting the text into fragments without losing important details was tricky. I learned that choosing the right fragment size (like 128 tokens) is super important.</li><li><strong>Understanding Trade-offs:</strong> While FragmentStream Attention saves memory, it’s not perfect for every situation. For really short texts, traditional attention might still work better.</li><li><strong>Not really Sure: </strong>I haven’t tested this model on a very huge dataset like i tried it on Kaggle’s free P100 gpu on 26,075,321 training samples and 1,368,819 test samples based on a healthcare related dataset by NIH Senior Health and here is the glimpse of the output:</li></ol><pre>question = &quot;Hello&quot;<br>test_generation(question, temperature=0.0)<br><br>Generating answer (temperature=0.0)...<br><br>Results:<br>A: Hello Hi , I have gone through your query and understand your concern . You have a history of allergic reaction to the skin . It is a common problem of the skin . It is a common condition of the skin . It is a common cause of the skin . It is a common cause of the skin . It is a fungal infection . It is a common cause of the skin infection . It is a common cause of the skin . It is a fungal infection . It is a common cause of the skin infection . It is a fungal infection . It is a common cause of the skin infection . It is a fungal infection . It is a fungal infection . It is a common cause of the skin . It is a fungal infection . It is a common cause of the skin . It is a fungal infection . It is a fungal infection . It is a common cause of the skin infection . It is a fungal infection . It is a common cause of the skin . It is a fungal infection . It is a common</pre><pre>question = &quot;I am having pain in my head&quot;<br>test_generation(question, temperature=0.5)<br><br>Generating answer (temperature=0.5)...<br><br>Results:<br>A: I am having pain in my head Thanks for writing to Chat Doctor . Since you have history of pain in chest pain , I would suggest you to rule out cardiac cause for your symptoms . You may need to see a doctor for a diagnosis and treatment . Till then , you may need to take an antacid like omeprazole and antacid . If you should go for a chest x - ray and chest x - ray and blood test to rule out any cardiac diseases . If needed x - ray is normal then no need to worry . Hope I have answered your question , if you have doubt then I will be happy to answer . Thanks for using Chat Doctor . Wish you a very good health . Hi , I am a 32 year old woman . I have been experiencing pain in my left side of my left shoulder blade and on the lower left side of my neck . I have had a pain in my back . I had a pain in my left arm . It has gotten worse . I had a small bruise on my back of my back .</pre><h3><strong>Possible use cases</strong></h3><p><strong>Chatbots:</strong> To develop simple chatbot which can respond more smartly using context to generate smart responses but at very, very low cost.</p><p><strong>Expert Systems: </strong>To develop a domain specific Expert System instead of a general purpose ai.</p><p><strong>Efficiency: </strong>To develop language model as Efficient and faster as possible.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, my research into <strong>FragmentStream Attention</strong> is still a work in progress. As you can see from the outputs, the model is currently just predicting the next word, which is normal given that the dataset used is basic and focused on simple prompts. My goal is to refine it further and make it more efficient, ultimately creating very, very lightweight language model that works like more advanced ones.</p><p>The idea behind <strong>FragmentStream Attention</strong> is to make transformers more memory-efficient so they can run on smaller hardware without losing their ability to understand complex language. While it’s shown promising results, there’s still a lot to improve, especially when working with larger and more diverse datasets.</p><p>I plan to make this project open source, I am sharing this on <a href="https://github.com/YashRL/FragmentStream_Attention_llm"><strong>GitHub</strong></a> and Kaggle for the community to explore, contribute to, and improve. I truly appreciate any feedback or contributions to help me make this project even better. Thank you for reading, this was my first article also, Thankyou for your interest and support!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f178cbbd5f62" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>