<?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 Muhammad Amaan on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Amaan on Medium]]></description>
        <link>https://medium.com/@m-amaan?source=rss-308717412132------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3WdBV2yY8xF41CKaU5V_rA.jpeg</url>
            <title>Stories by Muhammad Amaan on Medium</title>
            <link>https://medium.com/@m-amaan?source=rss-308717412132------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:18:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@m-amaan/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[The Concurrency Token Crunch: How to Stop Nuking Your Own OAuth Sessions]]></title>
            <link>https://m-amaan.medium.com/the-concurrency-token-crunch-how-to-stop-nuking-your-own-oauth-sessions-52bc63955efe?source=rss-308717412132------2</link>
            <guid isPermaLink="false">https://medium.com/p/52bc63955efe</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Muhammad Amaan]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 12:26:45 GMT</pubDate>
            <atom:updated>2026-08-22T12:26:45.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9lcgvSpBO7O6xwmNkwrIA.png" /></figure><h3>Why reactive error handling in Python asyncio is a death sentence for third-party API integrations, and how to fix it with a Proactive Token Manager.</h3><p>If you are building an application that aggregates data from multiple third-party APIs, there is a silent concurrency bug waiting to destroy your users’ sessions.</p><p>I found this out the hard way during the development of a multi-platform analytics dashboard. I wrote code that was too fast, and my asynchronous requests ended up permanently revoking my own test accounts’ OAuth access.</p><p>Here is a deep dive into the “Concurrency Token Crunch,” why traditional reactive error handling fails at scale, and the exact architecture I engineered to solve it.</p><h3>The Architecture Context</h3><p>The platform I was building aggregates data across YouTube, TikTok, Patreon, Shopify, and Meta. Each platform enforces wildly different token lifespans:</p><ul><li><strong>YouTube:</strong> Expires in 1 hour.</li><li><strong>TikTok:</strong> Expires in 24 hours.</li><li><strong>Meta (Facebook &amp; Instagram):</strong> Expires in 60 days (long-lived access tokens).</li><li><strong>Patreon:</strong> Expires in 30 days.</li><li><strong>Shopify:</strong> Permanent offline access.</li></ul><p>When a user clicks “Generate Report,” the system needs to fetch analytics from all connected platforms simultaneously. To optimize for latency, my FastAPI backend fired off parallel requests using asyncio.gather.</p><p>The initial token refresh logic was standard, reactive boilerplate: wait for the API call to fail with a 401 Unauthorized, catch the exception, use the refresh token to get a new access token, and retry the request.</p><p>In a synchronous, single-threaded environment, this works fine. In an asynchronous environment, it is catastrophic.</p><h3>The Anatomy of a Race Condition</h3><p>Because the requests were parallelized, the naive reactive approach created a massive race condition.</p><p>If a YouTube token was expired, five concurrent coroutines would hit the 401 Unauthorized error at the exact same millisecond.</p><ol><li>All five tasks entered the except block simultaneously.</li><li>All five tasks sent a request to Google’s OAuth endpoint using the <em>same</em> refresh token.</li><li>Task 1 succeeded and was issued a new token pair.</li><li>Tasks 2 through 5 arrived milliseconds later with the old refresh token. Google’s security systems flagged this as a replay attack or a hijacked token.</li><li>The result? <strong>Google permanently revoked the user’s access grant.</strong></li></ol><p>If this had shipped to production, I would have been automatically logging my users out by trying to serve them faster.</p><h3>The Fix: Demand-Driven Proactive Lifecycle Management</h3><p>To fix this, I had to scrap the reactive try/except paradigm entirely. I engineered a proactive state manager to guarantee token validity <em>before</em> a downstream request is ever fired.</p><p>The solution consists of three core mechanics:</p><h3>1. The 300-Second Preemption</h3><p>The system no longer waits for a 401 error. Every API request routes through a get_valid_token() check. If expires_at - utcnow() &lt; 300s, the token is flagged for immediate refresh. This guarantees that any token handed to a worker has a minimum 5-minute safety window to complete its API operations.</p><h3>2. The Indexed Fast Path</h3><p>To prevent this check from becoming a massive I/O bottleneck, the token query hits a composite index (user_id, platform) in Supabase PostgreSQL. Valid tokens bypass the refresh logic entirely and are returned in ~1.8ms.</p><h3>3. Async Mutex Gating (The Double-Check Lock)</h3><p>To kill the race condition, the token refresh mutation is gated behind a per-user asyncio.Lock().</p><p>When five parallel tasks hit the 5-minute expiry buffer simultaneously, Task 1 acquires the lock and executes the API call. Tasks 2–5 yield control back to the Python event loop. Once Task 1 commits the new token pair to the database, the lock releases.</p><p>Crucially, the waiting tasks perform a <strong>double-check</strong> once they acquire the lock. They re-read the database, realize the token was already refreshed by Task 1, and seamlessly resume using the newly minted token without ever hitting the OAuth endpoint.</p><p>Here is the exact implementation:</p><pre>async def get_valid_token(self, user_id: str, platform: Platform, platform_user_id: Optional[str] = None) -&gt; Optional[TokenData]:<br>    <br>    token_data = await self.get_token(user_id, platform, platform_user_id)<br>    if not token_data: return None<br><br>    # 1. The Fast Path (No lock needed)<br>    if token_data.status == TokenStatus.VALID and not token_data.expires_soon:<br>        return token_data<br>    # 2. Async Mutex Gating to prevent OAuth Race Condition<br>    lock = self._get_refresh_lock(user_id, platform)<br>    async with lock:<br>        <br>        # Double-check: Another task may have refreshed while waiting for lock<br>        token_data = await self.get_token(user_id, platform, platform_user_id)<br>        <br>        if token_data.status == TokenStatus.VALID and not token_data.expires_soon:<br>            return token_data  # Yields fresh token without hitting API<br>        # 3. We are the lock winner - perform the actual refresh<br>        try:<br>            valid_token = await token_manager.get_valid_token(token_data)<br>            if valid_token.access_token != token_data.access_token:<br>                await self.save_token(valid_token) # Commit to Supabase DB<br>            <br>            return valid_token<br>        except HTTPException as e:<br>            raise</pre><h3>Architectural Trade-offs &amp; Alternatives</h3><p>Engineering is about choosing your trade-offs. Here is why I structured the system this way instead of using common alternatives:</p><h3>Why not cache tokens in Redis?</h3><p>Hitting PostgreSQL on every API request adds overhead. Storing access tokens in Redis is the industry standard for high-throughput systems. However, for a V1 product optimizing for operational simplicity, introducing a separate caching layer (and managing cache invalidation across distributed workers during user disconnects) adds unnecessary infrastructure weight. By relying on a strict composite index in Postgres, we maintained ~1.8ms read times. Adding Redis would save &lt;1.5ms at the cost of significant system complexity.</p><h3>Why not use a background worker (Celery) to refresh tokens?</h3><p>A common alternative is running a background cron job that sweeps the database every 5 minutes and refreshes expiring tokens asynchronously, entirely decoupled from the user request.</p><p>The problem? <strong>API quota exhaustion.</strong> If a user connects 5 accounts but doesn’t log into the dashboard for three weeks, a background sweeper will consume thousands of third-party API quota units daily just to keep tokens warm for a dormant user. The Demand-Driven approach aligns API expenditure strictly 1:1 with active user sessions.</p><h3>The Limits of asyncio.Lock</h3><p>It is important to note that asyncio.Lock() operates strictly within a single Python process&#39;s event loop. It is the perfect fire-extinguisher for a single-worker MVP. However, as the system scales horizontally across multiple Uvicorn workers or Kubernetes pods, the local lock boundary dissolves. The planned V2 migration delegates this concurrency control directly to the ACID-compliant database layer using Postgres row-level locking (SELECT ... FOR NO KEY UPDATE), achieving distributed state synchronization without requiring Redis Redlock.</p><h3>The Takeaway</h3><p>When building asynchronous backend systems, you cannot rely on synchronous error-handling paradigms. Reactive token refreshing will inevitably trigger race conditions that compromise your infrastructure and user experience.</p><p>By shifting to a proactive, state-aware lifecycle manager with properly gated concurrency, you protect your API quotas, secure your user sessions, and build a system that actually scales when you step on the gas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52bc63955efe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SustainTip: Building a Greener Tomorrow with Daily AI-Powered Habits (Project in Progress)]]></title>
            <link>https://m-amaan.medium.com/sustaintip-building-a-greener-tomorrow-with-daily-ai-powered-habits-project-in-progress-6bfcaae502c8?source=rss-308717412132------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bfcaae502c8</guid>
            <category><![CDATA[sustainable-development]]></category>
            <category><![CDATA[sustainability]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[green-habits]]></category>
            <category><![CDATA[solution-challenge-2025]]></category>
            <dc:creator><![CDATA[Muhammad Amaan]]></dc:creator>
            <pubDate>Sun, 04 May 2025 18:49:18 GMT</pubDate>
            <atom:updated>2025-05-04T18:49:18.194Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: One Tip at a Time</h3><p>In a world increasingly affected by climate change, it’s easy to feel overwhelmed by the magnitude of the problem. While large-scale reforms are essential, the role of individual behavior cannot be ignored. Yet, for many people, adopting a sustainable lifestyle is often hindered by one factor: complexity. What if there were a way to make eco-conscious living simple, daily, and deeply personalized?</p><p>That’s the vision behind <strong>SustainTip</strong> — a mobile app currently under development as part of a Google Solution Challenge project at COMSATS University, Attock. The goal is straightforward yet impactful: deliver one green, actionable, personalized habit every day to each user, powered by Gemini and backed by robust technology.</p><p>This article takes a deeper look at how the app works, the thought process behind it, the technologies we’re using, and where we are in our development journey.</p><h3>🌍 The Problem We’re Solving</h3><p>Let’s face it: “Use less plastic” is good advice, but it’s vague. Real behavior change requires <strong>contextual and practical</strong> guidance.</p><p>Sustainability isn’t one-size-fits-all. Someone living in a city will have different green opportunities than someone in a rural area. Our app bridges that gap using AI to personalize advice in a way that’s:</p><ul><li><strong>Relevant</strong></li><li><strong>Localized</strong></li><li><strong>Simple to act on</strong></li></ul><h3>🔧 Tech Behind the Magic</h3><p>We’re leveraging a modern and scalable tech stack to bring this vision to life:</p><ul><li><strong>Frontend:</strong> Flutter (cross-platform mobile development)</li><li><strong>Backend:</strong> Firebase (Firestore, Cloud Functions, Auth)</li><li><strong>AI Engine:</strong> Google Gemini via Vertex AI</li><li><strong>Communication:</strong> Firebase SDKs and REST APIs</li></ul><p>This architecture allows us to handle:</p><ul><li>Secure user authentication</li><li>Real-time tip delivery</li><li>AI-driven content generation</li><li>User preference tracking</li></ul><h3>Key Functionalities (And Why They Matter)</h3><p>Here are some of the app’s core features and the rationale behind them:</p><h3>1. Daily Tip Delivery</h3><p>Each day, users receive a fresh, simple, and meaningful sustainability tip. This daily rhythm is critical for habit formation.</p><h3>2. Personalization</h3><p>Users select their preferred focus areas (e.g., Home, Food, Travel), and tips are generated accordingly using AI — making suggestions feel relevant rather than random.</p><h3>3. Local Context Awareness</h3><p>Thanks to Gemini’s flexible language capabilities, tips are generated considering local behaviors, seasons, and lifestyle nuances.</p><h3>4. Save for Later</h3><p>Users can favorite tips they find useful, creating a personal library of habits to revisit or act on at their own pace.</p><h3>Development Status: Work in Progress</h3><p>As of now, <strong>SustainTip is in active development</strong>, with major components like the core functionality, UI skeleton, and backend services being implemented. We are currently focused on:</p><ul><li><strong>Improving AI prompt design</strong> to ensure the Gemini model generates relevant and realistic tips</li><li><strong>Integrating AI output with Firebase workflows</strong></li><li><strong>Building and testing user flows</strong> like onboarding, preferences, and saving tips</li><li><strong>Enhancing UI/UX</strong> for simplicity and delight</li></ul><p>We’ve made steady progress over the past few weeks and are excited to announce that the <strong>project will be completed within the next 5 to 6 days</strong>. The upcoming milestone is a working prototype with tip generation and personalized delivery fully functional.</p><h3>What We’ve Learned So Far</h3><p>This project has already been a massive learning opportunity for us, especially in these areas:</p><ul><li><strong>Prompt Engineering:</strong> Crafting good prompts for generative AI models is both an art and a science. Vague prompts yield vague outputs, while structured prompts produce better context-aware results.</li><li><strong>Hybrid Content Strategy:</strong> Not every tip needs to be generated from scratch. We’re blending static, curated tips with dynamic AI-generated ones to ensure quality and variety.</li><li><strong>Designing for Engagement:</strong> Delivering a tip is easy. Getting users to <em>care</em> about it daily? That’s the real challenge. We’re exploring ways to gamify the experience and provide gentle reminders.</li></ul><h3>🔮 What’s Next?</h3><p>After our MVP (minimum viable product) is up and running, we’re planning:</p><ul><li>🎮 <strong>Gamification</strong> (streaks, challenges, badges)</li><li>🌐 <strong>Multi-language support</strong></li><li>🧑‍🤝‍🧑 <strong>Community features</strong> (share your tips, inspire others)</li><li>🪄 <strong>Smart reminders</strong> to keep the habit loop alive</li></ul><h3>🌱 Final Thoughts</h3><p><strong>SustainTip isn’t just an app.</strong> It’s a daily nudge. A gentle reminder that real climate action starts with small, consistent steps.</p><p>We believe that with the right tools, <em>anyone</em> can live a more eco-friendly life — without feeling overwhelmed, guilty, or confused.</p><p>The world needs change, and sometimes, all it takes is one tip at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bfcaae502c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GDGoC Comsats Attock ML/DL Fellowship: Week 1 Recap]]></title>
            <link>https://m-amaan.medium.com/gdgoc-comsats-attock-ml-dl-fellowship-week-1-recap-1f72e94e432f?source=rss-308717412132------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f72e94e432f</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[team-building]]></category>
            <category><![CDATA[fellowship]]></category>
            <category><![CDATA[google-developer-group]]></category>
            <category><![CDATA[weekly-update]]></category>
            <dc:creator><![CDATA[Muhammad Amaan]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 15:28:08 GMT</pubDate>
            <atom:updated>2025-03-08T15:28:08.894Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s been an exciting week for Developer Groups on Campus(GDGoC) Comsats Attock! As a Community Engagement Lead, I’m proud to see the launch of our ML/DL fellowship, led by Nimra Waqar. While the concepts we covered are not new to me, it&#39;s a welcome refresher; seeing the enthusiasm and learning progress of our fellows has been incredibly rewarding.</p><p>This fellowship is a significant step in enhancing our core team’s capabilities, and it’s been fantastic to see everyone, including myself, engage so passionately.</p><p><strong>Starting with the Basics: AI, ML, DL, and Data Science:</strong></p><p>Our journey began with demystifying the core terminologies. We watched a fantastic video by Krish Naik and read an informative article ‘<a href="https://towardsdatascience.com/data-science-vs-artificial-intelligence-vs-machine-learning-vs-deep-learning-9fadd8bda583/">Data Science vs. Artificial Intelligence vs. Machine Learning vs. Deep Learning</a>’, which really helped clarify the distinctions between Artificial Intelligence (AI), Machine Learning (ML), Deep Learning (DL), and Data Science.</p><p>To recap, we learned that:</p><ul><li><strong>AI</strong> represents the broad concept of machines mimicking human intelligence.</li><li><strong>ML</strong> is a subset of AI where machines learn from data without explicit programming.</li><li><strong>DL</strong> is a specialized area of ML that uses neural networks with multiple layers for complex data analysis.</li><li><strong>Data Science</strong> is the multidisciplinary field that extracts knowledge from data.</li></ul><p>It’s a classic nested structure, with AI encompassing ML, which in turn encompasses DL. Data Science provides the tools and techniques to navigate them all.</p><p><strong>Python from First Principles: No Libraries Allowed!</strong></p><p>Task two was a deep dive into Python fundamentals, requiring us to build functions from scratch — no libraries! This was a great exercise in solidifying our understanding of the underlying math. We tackled:</p><ul><li>Calculating the mean, median, and mode, is a classic statistics refresher.</li><li>Computing variance and the standard deviation is vital for understanding data spread.</li><li>Determining Euclidean distance is crucial for measuring data point similarity.</li><li>Implementing the sigmoid function: A cornerstone of neural networks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/1*G582y2GR_eV09LpJra1Mcg.png" /></figure><p>The main focus of the first week was not to understand these concepts in depth(we will cover that later) but to know how to write mathematical formulas in Python. This hands-on approach reinforced the importance of the mathematical foundations in ML/DL.</p><p><strong>Mathematical Muscle: MSE, RMSE, Cosine Similarity, and More</strong></p><p>Task three pushed us further, requiring us to implement:</p><ul><li>Mean Squared Error (MSE) and Root Mean Squared Error (RMSE) are essential for regression model evaluation.</li><li>Cosine similarity is a key metric for vector similarity.</li><li>Linear regression is a fundamental predictive modeling technique.</li><li>The softmax function: Used for multiclass classification.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*aBM5NUj4wpGQFXbgPoO0ng.png" /><figcaption>softmax</figcaption></figure><p>Doing this without libraries was a bit challenging but valuable exercise, ensuring we truly understood the underlying formulas and their implementation.</p><p><strong>Kaggle and Practical Application</strong></p><p>We also explored Kaggle, completing the first exercise of the “Intro to Programming” course. The interactive exercises were a fun and engaging way to apply our knowledge.</p><p>All my work of fellowship is available on my GitHub repository and will be updated regularly: <a href="https://github.com/AmaanAwan/ML-DL-fellowship-by-GDGoC-Comsats-Attock">ML/DL fellowship by GDGoC Comsats Attock</a></p><p><strong>Reflections and Endorsement</strong></p><p>While the first week served as a refresher for me, I’m incredibly impressed with the progress of our fellows and the excellent start Nimra has provided. This fellowship is a testament to the dedication of our team and the eagerness of our community to learn.</p><p>Key takeaways:</p><ul><li>This fellowship is a great step to upscale our core team skills.</li><li>Understanding the math behind ML/DL is just as important as coding skills.</li><li>Python is an indispensable tool.</li><li>Platforms like Kaggle make learning engaging and accessible.</li><li>GitHub is important to keep learnings open source, collaborative learning, and organized project management.</li><li>The fellowship tasks are designed to create a strong mathematical and programmatic base.</li></ul><p>I’m excited for the upcoming weeks and the continued growth of our community. Stay tuned for more updates on our ML/DL journey!</p><p><em>Amaan signing off!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f72e94e432f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Attention Mechanism: Need, Working and Benefits]]></title>
            <link>https://m-amaan.medium.com/understanding-attention-mechanism-need-working-and-benefits-5e4ef2880129?source=rss-308717412132------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e4ef2880129</guid>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rnn]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Muhammad Amaan]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 15:53:38 GMT</pubDate>
            <atom:updated>2025-01-10T15:53:38.961Z</atom:updated>
            <content:encoded><![CDATA[<p>Surprisingly, The concept of ‘attention’ is quite similar in both human language and neural networks: focusing on something with interest. Just as humans focus their minds on specific details, neural networks do something called an attention mechanism to prioritize certain information within the data they process.</p><p>This reading is all you need to know about attention in one shot. Understanding word embeddings and RNNs will be to your advantage. Starting from the question of why we even need something new(attention) when we already have RNNs for handling sequential data and whether is it useful?</p><h3>Why there was the need for Attention?</h3><p>RNN is beneficial for handling sequential data but there were some significant problems like:</p><ul><li><strong>Limited Context:</strong> RNNs process information sequentially, one element at a time. This makes it difficult for them to capture long-range dependencies in sequences.</li><li><strong>Vanishing &amp; Exploding Gradient:</strong> The vanishing gradient problem happens when gradients get too small during backpropagation, making early layers learn very slowly. This is because weights less than one multiply repeatedly, causing gradients to shrink exponentially. On the other hand, the exploding gradient problem occurs when gradients become too large, making training unstable. This happens when weights greater than one multiply repeatedly, causing gradients to grow exponentially. Both issues make training recurrent neural networks (RNNs) difficult.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*iOZBOzAYhgSCoRILiQ1Csg.png" /></figure><ul><li><strong>Sequential Processing Bottleneck:</strong> RNNs process data one element (word, token) at a time. The output from the current step becomes part of the hidden state, which is used to process the next element. This can be computationally slow, especially for long sequences.</li></ul><h4>How can we build a more effective architecture for sequence modeling?</h4><p>Rather than thinking about things time-step by time-step in isolation let&#39;s take a sequence for what it is and learn a Neural Network model that can tell us what parts of the sequence are actually the important ones. Only conveying the important information that the network should be capturing and learning.</p><p><strong><em>Our goal is to:</em></strong></p><p><strong><em>i. Identify which parts to attend to</em></strong></p><p><strong><em>ii. Extract the features with high attention</em></strong></p><p>So the Transformer Model is built. The Transformer was proposed in the paper <a href="https://arxiv.org/abs/1706.03762"><em>Attention is All You Need</em></a>.</p><blockquote>“Transformer is a type of Neural network Architecture that is build on attention as its foundational mechanism.”</blockquote><p>To get a basic understanding of the Transformers model, check out my blog <a href="https://medium.com/@m-amaan/transformer-models-a-detailed-beginner-guide-eb765cce9740">here</a>.</p><h3>What is attention?</h3><blockquote>“Attention is a mechanism that dynamically highlights different parts of the input data that are more relevant or important when making predictions or generating outputs. It allows the model to focus on relevant parts of the input sequence, helping it to understand and process the data more effectively.”</blockquote><h3>Why is it useful?</h3><p>Applying the attention mechanism in machine learning models, such as in the transformer architecture, carries many benefits that enhance their overall performance. Here are some key advantages:</p><ul><li><strong>Capturing Long-Range Dependencies: </strong>Attention allows the model to focus on relevant parts of the input sequence regardless of their distance from the current position. This enables better handling of long-range dependencies, which is crucial for understanding context in tasks like language translation.</li><li><strong>Context-awareness:</strong> By weighing the importance of different parts of the input sequence based on their relevance to the current token being processed, the attention mechanism helps the model understand the context better.</li><li><strong>Parallelization:</strong> Unlike RNNs, which process sequences sequentially, attention mechanisms allow for parallel processing of the entire input sequence. This independence allows for parallel processing across GPUs, significantly speeding up training compared to RNNs. Parallelization also makes attention-based models like Transformers highly scalable and suitable for handling large datasets and complex tasks.</li></ul><h4><strong>Analogy:</strong></h4><p>Here’s an analogy that will make it more clear to understand the benefits of Attention. Imagine analyzing a sentence.</p><ul><li>RNNs would be like reading the sentence word by word, analyzing each word based on the previous ones.</li><li>Transformers would be like reading the entire sentence at once, understanding how each word relates to others without a strict order.</li></ul><h3>How does the Attention mechanism work?</h3><p>Embeddings for each word are the high-dimensional vector that encodes the meaning of a particular word(actually a token) and its position. Entries of this vector are enough to tell what the word is and where it exists in the context.</p><p>Embeddings for each word are the high-dimensional vector that encodes the meaning of a particular word. The problem is that due to parallelism in the transformer, there is lack of information about the order of elements in the sequence. So we have to also add positions(sequence) to word embeddings.<br><strong>Positional encoding</strong> is used to add information about the position of each token(word) in a sequence into the model. it works by generating a unique vector for each position in a sequence and then adding a vector to the corresponding word embedding. The resulting vector contains both information about the word and position of that word. This resulting vector is then fed into Transformer and here comes the attention mechanism.</p><p>To understand the working of Attention we first have to understand what is Query, Key and Value. And how these are related.</p><p><strong>Query vector</strong> is some sort of “question vector” that has a much smaller dimension than an embedding vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*zBc9e4lmwcge_iHCDs4pow.png" /></figure><p><strong>Key Vector</strong> is kind of answering the Queries. Just like a Query matrix, it maps the embedding vectors to the same smaller dimensional space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*GeYstdRyH_n0M4GCUK0IfQ.png" /></figure><p>The attention mechanism concept comprises of several terminologies, including attention score, attention weighting, and attention pattern. We’ll go over each one step by step.</p><p><strong>Attention score is the measure of similarity between Queries and Keys.</strong></p><p>But how do we compute the similarity between keys and queries? The answer is that the closer the vector, the more similar they are. It is computed using a dot product. If the dot product of both is large, it means the Key “attends to” Query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*bqRyOgZe_-7OpW8xVgFv-g.png" /></figure><p>This dot product gives us a grid of values that can be any real number from -∞ to +∞ given how relevant each word is to updating the meaning of every other word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*OJl3_ZLO7NOMJfRIBK4uRw.png" /></figure><p>To make numbers in a grid between 0 and 1, and also to make a probability distribution such that each column adds up to 1 we use an activation function called “Softmax”. This is attention weighting.</p><p><strong>Attention Weighting is the normalized attention score, transformed into a probability distribution using the softmax function, indicating the importance of each key for the given query.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*odpizXf7H4zDPWrzFtM-sg.png" /></figure><p>Now we have a normalized grid that contains the weights depending on how relevant each key is to query. This normalized grid is called Attention Pattern.</p><p><strong>Attention Pattern is the resulting distribution of attention weights across the sequence, showing where the model is focusing its attention.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*W5tgeo3pcLX_J71SyrnMig.png" /></figure><p>If we look at the original Transformer paper “Attention is all you need”, there is a very compact way they write this all down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57Z6PfCbE5z9KdvXs8GKzw.png" /></figure><p><em>Here the variables Q and K represent full arrays of Query and Key vectors respectively. √dk​​ is the scaling factor.</em></p><p>The thing we mentioned but didn’t discussed yet is Value.</p><p><strong>Value vector</strong> holds the actual information about each element. It’s the data the query vector wants to access, depending on how relevant the key is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*sJ_sA4w3YSXWpI7n15WBew.png" /></figure><p>Value vector multiplies with corresponding attention weight. Then sum of the resulting answers in each column is taken. If we see it from attention pattern point of view, it may look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*MZ0VY2PT5gQJhU3571Y1dQ.png" /></figure><p>This gives us the sequence of changes. Adding all of those changes into corresponding embeddings produces a full sequence of more refined embeddings coming out of the attention block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*k6ujBy_x4rR7La0qCp2SoA.png" /></figure><p>One thing I haven’t mentioned yet is that during the training process, when the model runs on text example all weights(Wq,Wk,Wv) are slightly adjusted and tuned to either reward or punish it based on how high a probability it assigns to the next word in the passage.</p><blockquote><strong>These operations above form a single self-attention head that can plug into a larger network. Each head attends to a different part of the input.</strong></blockquote><p>Have you ever heard of Cross-Attention and Multi-Head Attention?</p><p><strong>Cross Attention</strong> involves models that process two distinct types of data like audio input of speech and ongoing transcripion.</p><p>All we discussed earlier is the working of a single Attention head. <strong>Multi-head attention</strong> combines multiple attention heads (think of them as working in parallel). Each head focuses on slightly different aspects of the relationships between elements in the sequence. The final output is a combination of the information captured by all the heads, giving the model a richer understanding of the data.</p><h3>Attention in a Nutshell.</h3><p>“Attention is a mechanism that allows the model to focus on specific parts of the input data.”</p><p>The simplest way to describe the attention mechanism is in four steps:</p><p>i. Encode position information</p><p>ii. Extract Query, Key &amp; Value</p><p>iii. Compute Attention weighting</p><p>iv. Extract features with High Attention</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*lO2SFjNGEvNlGRFytDLeGQ.png" /></figure><p>Overall, attention mechanisms are a crucial innovation in neural network architecture that significantly enhance the model’s ability to handle complex tasks, improve performance, and provide better interpretability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e4ef2880129" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformer Models: A Beginner Guide]]></title>
            <link>https://m-amaan.medium.com/transformer-models-a-detailed-beginner-guide-eb765cce9740?source=rss-308717412132------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb765cce9740</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Muhammad Amaan]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 06:19:16 GMT</pubDate>
            <atom:updated>2024-07-13T09:18:58.748Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Transformers are a model architecture in Machine Learning used for processing and generating sequential data, such as text.</p><p>To put it simply:</p><blockquote><strong><em>“A transformer is a type of artificial intelligence model that learns to understand and generate human-like text by analyzing patterns in large amounts of text data.”</em></strong></blockquote><p>Do you know? Transformer models power Natural Language Processing, letting computers understand language like never before.</p><h3>Revolutionizing NLP: How Transformers are Used for Various Tasks</h3><p>Transformers have revolutionized natural language processing (NLP) and have been extended to other areas like computer vision and audio processing. Transformer models are used to solve all kinds of NLP tasks. Some functionalities that are available in thepipeline() function of Transformer Library in Python are:</p><ul><li>feature-extraction (get the vector representation of a text)</li><li>fill-mask (fill the blanks of a given text)</li><li>ner (named entity recognition)</li><li>question-answering</li><li>sentiment-analysis</li><li>summarization</li><li>text-generation</li><li>translation</li><li>zero-shot-classification (allows you to specify which labels to use for the classification, so you don’t have to rely on the labels of the pre-trained model)</li></ul><p><em>Check out these pipelines implementation </em><a href="https://colab.research.google.com/drive/1nwkaU9DgzL0z6glxQ-bNVTEREJ55Rux5?usp=sharing"><em>here</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PRWySW3Pihjjy-qc.png" /></figure><h4>Transformers: A Powerful Architecture for Language Models</h4><p>The Transformer models such as GPT, BERT, BART, and T5 are trained as language models using vast quantities of raw text. They utilize self-supervised learning, where the training objectives are derived automatically from the input data, eliminating the need for human-labeled datasets.</p><p>Above, I’ve outlined some applications of Transformer Models in text processing. Curious about how these models work? Let’s break it down in a simple way for you.</p><h3>Inside Transformer Models: Understanding Their Workings</h3><p>Before diving into Transformer models architecture first understand some terminologies:</p><h4>Transfer Learning</h4><p>In transfer learning, you can leverage knowledge (features, weights, etc) from previously trained models for training newer models and even tackle problems like having fewer data for the newer task!</p><p><strong><em>Pretraining</em></strong> is the act of training a model from scratch: the weights are randomly initialized, and the training starts without any prior knowledge. This pretraining is usually done on very large amounts of data. Therefore, it requires a very large corpus of data, and training can take up to several weeks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLBHEmZR11pq88_WsiNpRw.png" /></figure><p><strong><em>Fine-tuning</em></strong>, on the other hand, is the training done after a model has been pretrained. The pretrained model was already trained on a dataset that has some similarities with the fine-tuning dataset. The fine-tuning process is thus able to take advantage of the knowledge acquired by the initial model during pretraining (for instance, with NLP problems, the pretrained model will have some kind of statistical understanding of the language you are using for your task).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6v3hLCI7f4q3RCQpIfRyg.png" /></figure><h4>Attention Layer</h4><p>A key feature of Transformer models is that they are built with special layers called <em>attention layers</em>. This layer will tell the model to pay specific attention to certain words in the sentence you passed it (and more or less ignore the others) when dealing with the representation of each word.</p><blockquote>Attention layers are used in both the encoder and decoder.</blockquote><h3>Transformer Basic Architecture</h3><p>Without going into complexities, here how you can understand the Transformer Architecture. If we start considering a Transformer for language translation as a simple black box, it would take a sentence in one language, English for instance, as an input and output its translation in English.</p><p>If we dive a little bit, we observe that this black box(Transformer) is composed of two main parts:</p><ul><li><strong>The encoder</strong> takes in our input and outputs a matrix representation of that input. For instance, the English sentence “How are you?”</li><li><strong>The decoder</strong> takes in that encoded representation and iteratively generates an output. In our example, the translated sentence “¿Cómo estás?”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8RgNPgZMe7y95Mm0.png" /></figure><p>The Transformer architecture was originally designed for translation. During training, the encoder receives inputs (sentences) in a certain language, while the decoder receives the same sentences in the desired target language. In the encoder, the attention layers can use all the words in a sentence. The decoder, however, works sequentially and can only pay attention to the words in the sentence that it has already translated.</p><p>Does all Transformer Models follow this architecture? <br>The answer to this question is <strong>NO</strong>. Not all Transformer models follow this exact architecture. The basic Transformer architecture, as described, consists of an encoder and a decoder designed for sequence-to-sequence tasks like translation. However, there are several variants of the Transformer architecture tailored for different NLP tasks.</p><h3>Categories</h3><p>Broadly, Transformers can be grouped into three categories:</p><ul><li>BERT-like (Encoder-only models)</li><li>GPT-like (Decoder-only models)</li><li>BART/T5-like (Encoder-decoder models)</li></ul><h4>1. Encoder models</h4><p>Encoder models use only the encoder of a Transformer model. At each stage, the attention layers can access all the words in the initial sentence. These models are often characterized as having “bi-directional” attention, and are often called <strong><em>auto-encoding models</em></strong>.</p><p>Encoder models are best suited for tasks requiring an understanding of the full sentence, such as sentence classification, named entity recognition (and more generally word classification), and extractive question answering.</p><blockquote><a href="https://aclanthology.org/N19-1423/">BERT</a> has Encoder-only architecture. Input is text and output is sequence of <a href="https://vaclavkosar.com/ml/Embeddings-in-Machine-Learning-Explained">embeddings</a>.</blockquote><h4>2. Decoder models</h4><p>Decoder models use only the decoder of a Transformer model. At each stage, for a given word the attention layers can only access the words positioned before it in the sentence. These models are often called <strong><em>auto-regressive models</em></strong>.</p><p>The pretraining of decoder models usually revolves around predicting the next word in the sentence. These models are best suited for tasks involving text generation.</p><blockquote><a href="https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf">GPT-2</a> has Decoder-only architecture. Input is text and output is the next word (token), which is then appended to the input.</blockquote><h4>3. Encoder-decoder/ Sequence-to-sequence models</h4><p>Encoder-decoder models (also called <strong><em>sequence-to-sequence models</em></strong>) use both parts of the Transformer architecture. At each stage, the attention layers of the encoder can access all the words in the initial sentence, whereas the attention layers of the decoder can only access the words positioned before a given word in the input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/0*hGx4hRnCQ5j5xAr1.png" /></figure><p>Sequence-to-sequence models are best suited for tasks revolving around generating new sentences depending on a given input, such as summarization, translation, or generative question answering.</p><blockquote><a href="https://arxiv.org/abs/1910.10683">T5</a> has <a href="https://arxiv.org/abs/1706.03762">Encoder-Decoder or Full-Transformer</a>. Input is text and output is the next word (token), which is then appended to the decoder-input.</blockquote><h3>Limitations</h3><p>Pretrained models are powerful yet inherently limited. They are trained on extensive datasets that may contain a mix of high-quality and problematic content from the internet. Consequently, <strong>there’s a risk of the model producing biased content</strong>, including sexist, racist, or homophobic material. Merely fine-tuning the model with specific data does not eradicate these biases.</p><h4>Helping Material:</h4><p>This reading is for beginners only if you want to learn more about Transformers, checkout following links:</p><p>[1] <a href="https://www.datacamp.com/tutorial/how-transformers-work"><em>How Transformers Work: A Detailed Exploration of Transformer Architecture | DataCamp</em></a></p><p>[2] <a href="https://arxiv.org/abs/1706.03762"><em>[1706.03762] Attention Is All You Need (arxiv.org)</em></a></p><p>[3]<em> </em><a href="https://towardsdatascience.com/attention-is-all-you-need-e498378552f9"><em>The Transformer Model. A Step by Step Breakdown of the… | by Kheirie Elhariri | Towards Data Science</em></a></p><p>[4]<em> </em><a href="https://towardsdatascience.com/transformer-models-101-getting-started-part-1-b3a77ccfa14d"><em>Transformer Models 101: Getting Started — Part 1 | by Nandini Bansal | Towards Data Science</em></a></p><p><strong><em>[1] and [2] are highly recommended</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb765cce9740" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>