<?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 Varun Sivamani on Medium]]></title>
        <description><![CDATA[Stories by Varun Sivamani on Medium]]></description>
        <link>https://medium.com/@varunsivamani?source=rss-4fae91d62ef9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9m8SdWcu1QD1tNOnBVC_4w.jpeg</url>
            <title>Stories by Varun Sivamani on Medium</title>
            <link>https://medium.com/@varunsivamani?source=rss-4fae91d62ef9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:27:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varunsivamani/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[Harness Engineering: The Path to Reliable AI Agents]]></title>
            <link>https://medium.com/@varunsivamani/harness-engineering-the-path-to-reliable-ai-agents-c964ae0ad14a?source=rss-4fae91d62ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c964ae0ad14a</guid>
            <category><![CDATA[agent-harness-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <dc:creator><![CDATA[Varun Sivamani]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 06:46:01 GMT</pubDate>
            <atom:updated>2026-10-09T06:46:01.550Z</atom:updated>
            <content:encoded><![CDATA[<p>Beyond models to reliable AI Agents</p><p>Harness is the runtime layer that makes an LLM/agent actually usable, controllable, and reliable in the real world.</p><h3>Whats a Harness?</h3><blockquote>Agent = Model + Harness</blockquote><blockquote>Harness = Instructions + Tools + Runtime</blockquote><blockquote>The <strong>agent decides what should happen</strong>. The <strong>harness controls how it happens</strong>.</blockquote><p>LLMs have evolved from systems that simply generate text into systems that can reason, use tools, execute code, interact with APIs, and perform multi-step tasks.</p><p>A model can decide that it needs to inspect a file, execute a Python script, query a database, call an API, and use the result to make its next decision. But the model itself shouldn’t be responsible for managing process lifecycle, permissions, execution environments, state persistence, retries, observability, resource limits, or recovery.</p><p>Those responsibilities belong to the <strong>harness</strong>. It is not one component, its a collection of infrastructure surrounding the agent.</p><h3>Components</h3><ul><li>Agent / LLM</li><li>Execution engine</li><li>Tool Runtime</li><li>State / Sessions</li><li>Sandbox / Security</li><li>Observability</li><li>Lifecycle manager</li><li>Resource management</li></ul><h3>Difference between M<strong>odel Engineering, Agent Engineering and Harness Engineering</strong></h3><pre>             ┌─────────────────────┐<br>             │ Harness Engineering │<br>             │  ┌───────────────┐  │<br>             │  │     Agent     │  │<br>             │  │  Engineering  │  │<br>             │  │ ┌───────────┐ │  │<br>             │  │ │   Model   │ │  │<br>             │  │ │Engineering│ │  │<br>             │  │ └───────────┘ │  │<br>             │  └───────────────┘  │<br>             └─────────────────────┘</pre><h3>1. Model Engineering</h3><p><strong>Focus:</strong> The model itself.</p><p><strong>Main Abstraction: </strong>Model</p><p><strong>Example: </strong>Fine-tuning Qwen on domain-specific data for better reasoning and understanding of domain knowledge.</p><h3>2. Agent Engineering</h3><p><strong>Focus:</strong> Turning a model into a system that can reason, use tools, and accomplish a goal.</p><p><strong>Main Abstraction: </strong>Agent loop</p><p><strong>Example: </strong>Building an incident-response agent.</p><h3>3. Harness Engineering</h3><p><strong>Focus:</strong> The runtime environment surrounding the agent.</p><p><strong>Main Abstraction: </strong>Execution environment</p><p><strong>Example: </strong>Building an agent runtime.</p><p>Harness engineering addresses questions such as:</p><ul><li>How are tools registered, invoked, and isolated?</li><li>How are sessions and intermediate results persisted?</li><li>How are timeouts, retries, and cancellation handled?</li><li>How are permissions and resource limits enforced?</li><li>How can an interrupted task recover?</li><li>How can engineers inspect what happened during an execution?</li></ul><p>For example, the harness surrounding an incident-response agent might enforce read-only access during investigation, require human approval before remediation, and record every tool invocation for auditing.</p><h4>Frameworks &amp; SDKs</h4><ul><li>LangGraph &amp; LangChain Deep Agents</li><li>OpenAI SDK</li><li>Claude Agent SDK</li></ul><h4>Popular Open-Source &amp; Model-Agnostic Harnesses</h4><ul><li>OpenCode</li><li>Pi Coding Agent</li><li>OpenHands</li></ul><h4>Popular &amp; Closed-Source Harnesses</h4><ul><li>Claude Code</li><li>Cursor</li><li>GitHub Copilot</li></ul><h3>Conclusion</h3><p>As AI agents take on longer-running and more consequential tasks, the engineering challenge extends beyond model intelligence.</p><p>Models determine what they can reason about. Agent logic organizes how they pursue goals. Harnesses govern how those goals are executed within a real environment.</p><p>Reliable agents need more than a good prompt and a collection of tools. They need controlled execution, persistent state, bounded resource consumption, meaningful observability, security enforcement, and recovery mechanisms.</p><p>The next stage of agent engineering is not simply about making models more capable. It is about building the infrastructure that allows their capabilities to be used responsibly and reliably.</p><p><strong>The model provides the intelligence. The harness provides the operational discipline. Production-grade agents need both.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c964ae0ad14a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Topic Modelling - You Can’t Read a Million Documents. Machines Can.]]></title>
            <link>https://medium.com/@varunsivamani/topic-modelling-you-cant-read-a-million-documents-machines-can-efa63142f0ba?source=rss-4fae91d62ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/efa63142f0ba</guid>
            <category><![CDATA[topic-modelling]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Varun Sivamani]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 18:21:01 GMT</pubDate>
            <atom:updated>2026-09-22T18:31:56.337Z</atom:updated>
            <content:encoded><![CDATA[<h3>You Can’t Process a Million Documents. Machines Can.</h3><p><em>How Topic Modelling went from matrix math to understanding meaning — LSA, LDA, and BERTopic explained</em></p><p>You open <strong>Netflix</strong> after a long day, scroll aimlessly for a few minutes, and somehow land on exactly the kind of show you were in the mood for -without ever typing what you wanted. It feels like magic.</p><p>It isn’t.</p><p>Behind that recommendation sits a machine that has quietly read more text than any human ever could. App store reviews left by frustrated users at midnight. Viewer comments. Show descriptions. Support tickets. Millions of lines of messy, unstructured, deeply human text-processed, organised, and mapped into themes, automatically, without a single person labelling any of it.</p><p>That’s topic modelling. And most people have never heard of it.</p><h3>Topic Modelling 💭?</h3><ul><li>A type of statistical modeling, leveraging unsupervised learning task to discover hidden semantic patterns in a text corpus and automatically identify topics that exist within it.</li></ul><h3>Topic Modeling Techniques</h3><h3>BERTopic (SOTA)</h3><ul><li>uses Sentence Transformer models as its first building block, converting sentences into dense vector representations (embeddings) that capture semantic meanings.</li></ul><blockquote>Step 1: Document Embedding</blockquote><blockquote>Step 2 : Dimensionality Reduction (UMAP)</blockquote><blockquote>Step 3: Clustering (HDBSCAN)</blockquote><blockquote>Step 4: Tokenisation (CountVectorizer)</blockquote><blockquote>Step 5: Topic Representation (c-TF-IDF)</blockquote><blockquote>Step 6: Fine-tuning (optional)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g7G6-4MHNEukxfvW.png" /></figure><h3>Latent Semantic Analysis (LSA)</h3><ul><li>NLP technique (Bag Of Words method) used to <strong>discover hidden relationships and concepts</strong> within unstructured text.</li></ul><blockquote><strong>Assumptions: </strong>There’s an inherent shape in word utilization that may be captured via the relationships b/w words and documents.</blockquote><h4>Singular Value Decomposition (SVD)</h4><ul><li>foundational matrix factorization technique which breaks down any matrix A into 3 simpler matrices: A = UΣVᵀ</li><li>relationships among phrases, documents and latent topics.</li><li>U = documents in “topic space”</li><li>Σ = importance weights of each topic (the singular values)</li><li>Vᵀ = words in “topic space.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*0p8r5xMeolha4M0t.jpg" /></figure><pre>docs = [<br>  &quot;NASA launched a new space shuttle into orbit&quot;,<br>  &quot;The space mission was a success after launch&quot;,<br>  &quot;The stock market saw record breaking revenue growth&quot;,<br>  &quot;Central bank raised interest rates to fight inflation&quot;,<br>  &quot;Space exploration and satellite technology drive innovation&quot;,<br>  &quot;Investment banking and financial markets showed strong growth&quot;,<br>]<br><br>Topic 1: space, launch, orbit, shuttle, mission, success<br>Topic 2: bank, market, inflation, revenue, interest, growth<br><br>Doc 1: Topic1=0.71, Topic2=0.02   ← space doc<br>Doc 2: Topic1=0.68, Topic2=0.01   ← space doc<br>Doc 3: Topic1=0.01, Topic2=0.74   ← finance doc<br>Doc 4: Topic1=0.02, Topic2=0.71   ← finance doc</pre><h4>Pros:</h4><ul><li>Bridges the gap between synonyms and polysemy (words with multiple meanings).</li><li>Reduces background noise and highlights core themes mathematically.</li><li>Works exceptionally well on large, well-defined corpora.</li></ul><h4>Cons:</h4><ul><li>“Bag-of-Words” limitations: It ignores word order and grammar, which can alter the true meaning of a sentence.</li><li>Static model: Unlike modern neural networks, traditional LSA cannot easily incorporate new data; it generally requires the entire model to be recomputed.</li></ul><h3>Latent Dirichlet Allocation (LDA)</h3><ul><li>NLP technique to <strong>discover hidden “topics”</strong> within large collections of text.</li><li>Unsupervised probabilistic model (Bayesian network — generative statistical model).</li><li>Given the words you observe in each document, what were the hidden topics that most plausibly generated them?</li></ul><blockquote><strong>Assumptions:</strong> documents are generated through a random, probabilistic process.</blockquote><blockquote><strong>Document = mixture of topics </strong>(climate science = 60% climate, 30% science)</blockquote><blockquote><strong>Topic = distribution of words</strong> (climate = high probs like temperature, CO2)</blockquote><pre>For each document:<br>  1. Roll a dice → pick a topic mixture<br>     e.g. Doc = 70% Politics + 30% Economy<br><br>  2. For each word in the document:<br>     Roll that topic&#39;s dice → pick a word<br>     e.g. Politics topic → &quot;election&quot; (prob 0.15), &quot;vote&quot; (0.12)...<br><br>Two Key distributions:<br>  θ (theta) ~ Dirichlet(α)   ← topic mixture per document<br>  φ (phi)   ~ Dirichlet(β)   ← word distribution per topic</pre><p><strong>Best suited for:</strong> Long-form documents (research papers, articles, reports) where interpretability is a priority.</p><p><strong>Limitation of LDA:</strong> LDA does not well capture the relationships between words because it is based on the statistical concept of a bag of words. Word order and context are completely ignored</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efa63142f0ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic AI]]></title>
            <link>https://medium.com/@varunsivamani/agentic-ai-fc31200e0b69?source=rss-4fae91d62ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc31200e0b69</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <dc:creator><![CDATA[Varun Sivamani]]></dc:creator>
            <pubDate>Thu, 04 Dec 2025 18:32:12 GMT</pubDate>
            <atom:updated>2025-12-04T18:32:12.517Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the AI That Thinks and Does</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kftGRF9UEZHGPpjU" /><figcaption>Photo by <a href="https://unsplash.com/@codzilla_swiss?utm_source=medium&amp;utm_medium=referral">AbsolutVision</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Agentic AI</strong> is an artificial intelligence system designed to achieve a specific goal with minimal supervision. It is composed of AI agents (ML models) that mimic human decision-making to solve problems in real time. In a multi-agent setup, each agent handles a specific subtask needed to reach the overall goal, and their activities are coordinated through AI orchestration.</p><h3>GenAI vs Agentic AI</h3><h4>Generative AI (GenAI)</h4><ol><li>Creates original content from data.</li><li>Reacts to user input.</li><li>Learns patterns from large datasets.</li><li>Operates without autonomous decision-making.</li></ol><h4>Agentic AI</h4><ol><li>Acts autonomously to achieve goals.</li><li>Proactively makes decisions based on context.</li><li>Adapts to changing situations.</li><li>Uses planning, reasoning, and learning to execute tasks.</li></ol><h3>Steps in Agentic AI</h3><ol><li>Perception</li><li>Reasoning</li><li>Goal Setting</li><li>Decision-Making</li><li>Execution</li><li>Learning and Adaptation</li><li>Orchestration</li></ol><h3>Use-Case: Personal Finance Management AI</h3><h4>1. Perception</h4><ul><li>AI/Agent collects data from the user (bank accounts, credit cards, investment platforms, spending apps, bill payments, subscriptions).</li></ul><h4>2. Reasoning</h4><ul><li>AI/Agent analyzes spending patterns, income trends, and investment performance. Detects anomalies or unusual transactions (helps in proper financial decisions.)</li></ul><h4>3. Goal Setting</h4><ul><li>Based on user input or predefined financial goals, Agent plans strategies like adjusting budgets, suggesting investments, or cutting unnecessary expenses.</li></ul><h4>4. Decision-Making</h4><ul><li>Agent evaluates multiple financial strategies, factors like potential returns, risk, and savings efficiency.</li></ul><h4>5. Execution</h4><ul><li>After making a decision, the Agent executes actions via tools.</li><li>Probable tools: schedule bill payments, make automatic transfers, or send alerts to the user.</li></ul><h4>6. Learning and Adaptation</h4><ul><li>Agent monitors the outcomes of its actions — did the user meet savings targets, was the user happy of the decisions?, or did investments perform as expected?</li><li>Reinforcement learning technique to perform better in the future.</li></ul><h4>7. Orchestration</h4><ul><li>Agent coordinates multiple subsystems to function efficiently.</li><li>Orchestration ensures these agents work together seamlessly, avoiding conflicts and optimizing resources.</li></ul><h3>Cons</h3><ul><li><strong>Goals can go wrong:</strong> If the Agent’s goals aren’t set carefully, it might find shortcuts that cause problems, like spreading false information or breaking things to “win.”</li><li><strong>Bad habits can grow:</strong> The Agent might keep doing something the wrong way over time if it focuses too much on one goal without limits.</li><li><strong>Teamwork can fail:</strong> When multiple AI agents work together, they can clash or get stuck, causing bigger problems if their tasks and rules aren’t clear.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc31200e0b69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mixture Of Experts explained]]></title>
            <link>https://medium.com/@varunsivamani/mixture-of-experts-explained-b36591f936a9?source=rss-4fae91d62ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b36591f936a9</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mixture-of-experts]]></category>
            <category><![CDATA[qwen3-coder]]></category>
            <dc:creator><![CDATA[Varun Sivamani]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 03:17:35 GMT</pubDate>
            <atom:updated>2025-08-28T03:17:35.095Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding MOEs in Qwen3–30B-A3B (<strong>Qwen3 Coder Flash)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-bALl39B1KH6tbRBkTb01A.png" /><figcaption><a href="https://www.eraser.io/diagramgpt">Credits</a></figcaption></figure><p>In the context of transformer models, a MoE has two main parts:</p><ol><li><strong>Sparse MoE layers</strong> replace the usual dense feed-forward network (FFN) layers. An MoE layer has several “experts” (for example, 8). Each expert is its own neural network. Usually, these experts are FFNs, but they can also be more complex networks — or even another MoE. This creates <em>hierarchical MoEs</em>.</li><li><strong>A gate network (or router)</strong> decides which tokens go to which expert. For example, a token “HI” might be sent to the second expert, while the token “HELLO” goes to the first expert. A token can also be sent to more than one expert. Choosing how to route tokens is one of the main challenges in MoEs. The router has learnable parameters and is trained together with the rest of the model.</li></ol><p>MoEs have <strong>advantages</strong> like <strong>efficient pretraining and faster inference</strong>, but they also bring <strong>challenges</strong>.</p><ul><li><strong>Training:</strong> They allow much more compute-efficient pretraining, but often struggle to generalize during fine-tuning, which can cause overfitting.</li><li><strong>Inference:</strong> Only part of the parameters are active during inference, so MoEs run faster than dense models with the same size. However, all parameters still need to be stored in memory, which means <strong>high VRAM requirements</strong>.</li></ul><blockquote><strong>For example</strong>, Mixtral 8x7B has about 47B parameters in memory (not 56B), because only the FFN layers are separate experts while other layers are shared. During inference, if two experts are used per token, the compute is similar to a 12B model instead of a full 14B model, since only 2x7B experts are active along with shared layers.</blockquote><p>Lets look into the code and then break it down clearly.</p><pre>class MoEFeedForward(nn.Module):<br>    def __init__(self, cfg):<br>        super().__init__()<br>        self.num_experts_per_tok = cfg[&quot;num_experts_per_tok&quot;]<br>        self.num_experts = cfg[&quot;num_experts&quot;]<br>        self.gate = nn.Linear(cfg[&quot;emb_dim&quot;], cfg[&quot;num_experts&quot;], <br>                        bias=False, dtype=cfg[&quot;dtype&quot;])<br><br>        # meta device - reduce memory pressure when initializing the model <br>        # before loading weights<br>        meta_device = torch.device(&quot;meta&quot;)<br>        self.fc1 = nn.ModuleList([<br>            nn.Linear(<br>                cfg[&quot;emb_dim&quot;], cfg[&quot;moe_intermediate_size&quot;],<br>                bias=False, dtype=cfg[&quot;dtype&quot;], device=meta_device<br>            )for _ in range(cfg[&quot;num_experts&quot;])]<br>        )<br>        self.fc2 = nn.ModuleList([<br>            nn.Linear(<br>                cfg[&quot;emb_dim&quot;], cfg[&quot;moe_intermediate_size&quot;],<br>                bias=False, dtype=cfg[&quot;dtype&quot;], device=meta_device<br>             )for _ in range(cfg[&quot;num_experts&quot;])]<br>        )<br>        self.fc3 = nn.ModuleList([<br>            nn.Linear(<br>                cfg[&quot;moe_intermediate_size&quot;], cfg[&quot;emb_dim&quot;],<br>                bias=False, dtype=cfg[&quot;dtype&quot;], device=meta_device<br>                <br>            )for _ in range(cfg[&quot;num_experts&quot;])]<br>        )<br><br>    def forward(self, x):<br>        b, seq_len, embed_dim = x.shape<br>        scores = self.gate(x)  # (b, seq_len, num_experts)<br>        topk_scores, topk_indices = torch.topk(scores, <br>                        self.num_experts_per_tok, dim=-1)<br>        topk_probs = torch.softmax(topk_scores, dim=-1)<br>        <br>        expert_outputs = []<br>        for e in range(self.num_experts):<br>            hidden = silu(self.fc1[e](x)) * self.fc2[e](x)<br>            out = self.fc3[e](hidden)<br>            expert_outputs.append(out.unsqueeze(-2))<br>        <br>        expert_outputs = torch.cat(expert_outputs, dim=-2)  <br>        # (b, t, num_experts, emb_dim)<br><br>        gating_probs = torch.zeros_like(scores)<br><br>        for i in range(self.num_experts_per_tok):<br>            indices = topk_indices[..., i:i+1]<br>            prob = topk_probs[..., i:i+1]<br>            gating_probs.scatter_(dim=-1, index=indices, src=prob)<br>        <br>        gating_probs = gating_probs.unsqueeze(-1)  # (b, t, num_experts, 1)<br>        <br>        # Weighted sum over experts<br>        y = (gating_probs * expert_outputs).sum(dim=-2)<br>        return y</pre><p>Config for the model:</p><pre>QWEN3_CONFIG = {<br>    &quot;vocab_size&quot;: 151_936,<br>    &quot;context_length&quot;: 262_144,<br>    &quot;emb_dim&quot;: 2048,<br>    &quot;n_heads&quot;: 32,<br>    &quot;n_layers&quot;: 48,<br>    &quot;head_dim&quot;: 128,<br>    &quot;qk_norm&quot;: True,<br>    &quot;n_kv_groups&quot;: 4,<br>    &quot;rope_base&quot;: 10_000_000.0,<br>    &quot;dtype&quot;: torch.bfloat16,<br>    &quot;num_experts&quot;: 128,<br>    &quot;num_experts_per_tok&quot;: 8,<br>    &quot;moe_intermediate_size&quot;: 768,<br>}</pre><h3>Lets break the code down one-by-one🔨</h3><p>Keeping only the number part and skipping all the other factors <em>(bias, dtype, device).</em></p><pre>class MoEFeedForward(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br><br>        self.num_experts_per_tok = 8<br>        self.num_experts = 128<br>        self.gate = nn.Linear(2048, 128)<br><br>        self.fc1 = nn.ModuleList([<br>            nn.Linear(2048, 768) # emb_dim -&gt; moe_intermediate_size<br>            for _ in range(128)  # num_experts<br>        ])<br><br>        self.fc2 = nn.ModuleList([<br>            nn.Linear(2048, 768) # emb_dim -&gt; moe_intermediate_size<br>            for _ in range(128) # num_experts<br>        ])<br><br>        self.fc3 = nn.ModuleList([<br>            nn.Linear(768, 2048)  # moe_intermediate_size -&gt; emb_dim<br>            for _ in range(128) # num_experts<br>        ])</pre><h3>We’ll break down Forward function into 4 steps:</h3><h4>Step 1: Passing the input through the gate layer.</h4><p>Input is passed through the Linear layer and the values are stored under score .</p><pre>b, seq_len, embed_dim = x.shape # (b, seq_len, 2048)<br><br>scores = self.gate(x)  # (b, seq_len, 2048) -&gt; (b, seq_len, 128)</pre><h4>Step 2: MOE function (as I call them)</h4><p>Here, we can consider two different steps as one, because these are independent and doesn’t alter the input but provides decision (routing decisions).</p><h4>Step 2.1:</h4><ul><li>Retrieves topk scores and topk indices from scores. (here, k=8)</li><li>Applies softmax to the topk_scores.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/0*K0PgMUYqwFbL6wqZ" /><figcaption>Softmax formula</figcaption></figure><p>Now each set of 8 scores becomes a <strong>probability distribution</strong>:</p><ul><li>all entries ≥ 0</li><li>they sum to 1 across the 8 experts for each token.</li></ul><pre># scores = (b, seq_len, 2048) -&gt; (b, seq_len, 128)<br><br>topk_scores, topk_indices = torch.topk(scores, 8, dim=-1)<br>topk_probs = torch.softmax(topk_scores, dim=-1)<br># (b, seq_len, 128) -&gt; (b, seq_len, 8)</pre><h4>Step 2.2:</h4><ul><li>Initializes all-zero probabilities (b, seq_len, 128).</li><li>For each token, fills in the top-8 positions with the softmaxed weights.</li><li>After the loop: each (b, seq_len, 128) row has exactly 8 non-zeros (sparse distribution).</li></ul><pre>gating_probs = torch.zeros_like(scores) # (b, seq_len, 128)<br><br>for i in range(8):<br>    indices = topk_indices[..., i:i+1]<br>    # (b, seq_len, 1)<br>    <br>    prob = topk_probs[..., i:i+1]<br>    # (b, seq_len, 1)<br>    <br>    gating_probs.scatter_(dim=-1, index=indices, src=prob)<br>    # (b, seq_len, 1) -&gt; (b, seq_len, 128)</pre><h4>Step 3:</h4><blockquote>For each expert e: output = FC3 [e]( SiLU ( FC1 ) * FC2 )</blockquote><blockquote>All the outputs are appended and concatenated.</blockquote><pre>expert_outputs = []<br>for e in range(128):<br>    hidden = silu(self.fc1[e](x)) * self.fc2[e](x) <br>    # (b, seq_len, 2048) -&gt; (b, seq_len, 768)<br><br>    out = self.fc3[e](hidden)<br>    # (b, seq_len, 768) -&gt; (b, seq_len, 2048)<br><br>    expert_outputs.append(out.unsqueeze(-2))<br>    # (b, seq_len, 2048) -&gt; (b, seq_len, 1, 2048)<br><br># Concatenate all experts: (b, seq_len, 1, 2048) -&gt; (b, seq_len, 128, 2048)<br>expert_outputs = torch.cat(expert_outputs, dim=-2)</pre><h4>Step 4:</h4><ul><li>Multiply expert outputs by their gating probabilities.</li><li>Since only 8 experts per token have nonzero weights, the weighted sum involves only those.</li><li>sum(dim=-2) collapses the expert dimension, leaving a <strong>mixture of expert outputs per token</strong>.</li></ul><pre># Weighted sum over experts<br>y = (gating_probs * expert_outputs).sum(dim=-2)<br># (b, seq_len, 128, 2048) * (b, seq_len, 128, 1)<br># gating_probs * expert_outputs : (b, seq_len, 128, 2048)<br># sum over experts (dim=-2)     : (b, seq_len, 2048)<br><br>return y<br># (b, seq_len, 2048), same as input embedding dimension</pre><h3>References</h3><ul><li><a href="https://huggingface.co/blog/moe#what-is-a-mixture-of-experts-moe">Mixture of Experts Explained</a></li><li><a href="https://github.com/rasbt/LLMs-from-scratch/tree/main/ch05/11_qwen3">LLMs-from-scratch/ch05/11_qwen3 at main · rasbt/LLMs-from-scratch</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b36591f936a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matryoshka Embeddings]]></title>
            <link>https://medium.com/@varunsivamani/matryoshka-embeddings-a2ce94b3d56a?source=rss-4fae91d62ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2ce94b3d56a</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[matryoshka-doll]]></category>
            <category><![CDATA[embedding-model]]></category>
            <dc:creator><![CDATA[Varun Sivamani]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 18:26:40 GMT</pubDate>
            <atom:updated>2025-06-07T18:26:40.243Z</atom:updated>
            <content:encoded><![CDATA[<p>Compact Dimensions, Maximum Impact</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9qGRPgMoDMnD9r-t.png" /><figcaption>[<a href="https://huggingface.co/blog/matryoshka#%F0%9F%AA%86-matryoshka-dolls">Source</a>]</figcaption></figure><p>As research in text embedding advanced, newer state-of-the-art models began generating embeddings with increasingly higher dimensional outputs — meaning each text input was represented by more numerical values. While this generally led to better performance on various tasks, it also introduced significant inefficiencies, especially for downstream applications like search, classification, or recommendation.</p><p>To address this trade-off between performance and efficiency, <a href="https://huggingface.co/papers/2205.13147">Kusupati et al. (2022)</a> proposed a new class of embedding models designed to retain effectiveness even when their embeddings are truncated. Their goal was to create representations that could be compressed to lower dimensions without significantly degrading task performance.</p><h4>Inspiration</h4><ul><li>“Matryoshka dolls”, also known as “Russian nesting dolls”, are a set of wooden dolls of decreasing size that are placed inside one another.</li><li>Similarly, Matryoshka embedding models are designed to prioritize important information in the earlier dimensions of an embedding, with less critical information stored in the later dimensions.</li><li>This structure enables the original high-dimensional embedding to be truncated while still preserving enough essential information to maintain strong performance on downstream tasks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e5PdqaLuXWwm9M_v.png" /><figcaption>[<a href="https://supabase.com/blog/matryoshka-embeddings">Source</a>]</figcaption></figure><h4>Matryoshka Representation Learning</h4><p>Matryoshka Representation Learning (MRL) can be seamlessly integrated into most existing embedding model training frameworks. Training an embedding model involves generating embeddings for a batch of inputs (e.g., sentences or documents) and computing a loss function that measures how well these embeddings capture the desired relationships (such as similarity or relevance). The optimizer then updates the model’s weights to minimize this loss, improving embedding quality over time.</p><p>With Matryoshka Embedding models, the training process follows a similar structure but introduces a key innovation: instead of evaluating only the full-size embeddings, the model also evaluates performance at multiple lower-dimensional truncations.</p><h4>Training Algorithm</h4><p>For each training batch:</p><ol><li><strong>Embeddings are generated</strong> (e.g., 768-dimensional).</li><li><strong>Truncated versions</strong> of those embeddings are created (768, 512, 256, 128, 64)</li><li><strong>Loss functions</strong> are applied at each of these dimensionalities, evaluating how well each truncated version performs the task (e.g., contrastive similarity, classification).</li><li><strong>All losses are summed</strong> to produce a single combined loss.</li><li>The optimizer updates the model weights to minimize this total loss.</li></ol><h4>Sample code block</h4><pre>from sentence_transformers import SentenceTransformer<br>from sentence_transformers.losses import CoSENTLoss, MatryoshkaLoss<br><br>model = SentenceTransformer(&quot;microsoft/mpnet-base&quot;)<br><br>base_loss = CoSENTLoss(model=model)<br>loss = MatryoshkaLoss(<br>    model=model,<br>    loss=base_loss,<br>    matryoshka_dims=[768, 512, 256, 128, 64],<br>    matryoshka_weight=[1, 1, 1, 1, 1],<br>)<br><br>model.fit(<br>    train_objectives=[(train_dataset, loss)],<br>    ...,<br>)</pre><blockquote>Training with MatryoshkaLoss does not incur a notable overhead in training time.</blockquote><h4><strong>Advantages of Matryoshka Embeddings</strong></h4><ul><li><strong>Reduced Storage Footprint:</strong> By allowing embeddings to be truncated without substantial loss in performance, Matryoshka Embeddings dramatically lower storage requirements. This is particularly beneficial for applications running on devices with limited memory or bandwidth.</li><li><strong>Accelerated Computation:</strong> With fewer dimensions to process, truncated embeddings enable faster inference and training, reducing both computational load and latency across various NLP pipelines.</li><li><strong>High Performance at Lower Cost:</strong> Remarkably, even when significantly reduced in size, Matryoshka Embeddings often retain competitive performance, matching or even exceeding that of traditional, higher-dimensional embeddings in many downstream tasks.</li></ul><h4><strong>Real-World Use Cases</strong></h4><ul><li><strong>Information Retrieval:</strong> Search engines and document retrieval systems can benefit from faster indexing and querying, without compromising accuracy, by using compact yet effective embeddings.</li><li><strong>Recommendation Systems:</strong> Matryoshka Embeddings make it possible to deliver high-quality recommendations for products, content, or services using models that are lightweight and scalable.</li><li><strong>Large Language Models (LLMs):</strong> Integrating Matryoshka Embeddings into LLM architectures can help reduce model size and speed up inference, making deployment more cost-effective while preserving output quality.</li><li><strong>Edge and Mobile AI:</strong> The ability to truncate embeddings without significant degradation makes this technique ideal for deploying AI on mobile or edge devices, where storage and compute power are limited.</li></ul><h3>References</h3><ul><li><a href="https://huggingface.co/papers/2205.13147">https://huggingface.co/papers/2205.13147</a></li><li><a href="https://huggingface.co/blog/matryoshka#%F0%9F%AA%86-matryoshka-dolls">https://huggingface.co/blog/matryoshka#%F0%9F%AA%86-matryoshka-dolls</a></li><li><a href="https://supabase.com/blog/matryoshka-embeddings">https://supabase.com/blog/matryoshka-embeddings</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2ce94b3d56a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain Routing]]></title>
            <link>https://medium.com/@varunsivamani/langchain-routing-e379b054bbd8?source=rss-4fae91d62ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e379b054bbd8</guid>
            <category><![CDATA[langchain-tools]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[agentic-applications]]></category>
            <dc:creator><![CDATA[Varun Sivamani]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 06:37:23 GMT</pubDate>
            <atom:updated>2025-04-22T17:19:55.064Z</atom:updated>
            <content:encoded><![CDATA[<p>A simplified approach</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KFDEsFQBRkT_OShB" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=medium&amp;utm_medium=referral">Shubham Dhage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>What is LangChain?</strong></h3><p><a href="https://www.langchain.com/"><strong>LangChain</strong></a> is an open-source framework designed to help developers build applications powered by <strong>Large Language Models (LLMs). </strong>It offers a wide range of features for natural language processing.</p><h3>Key Features</h3><ul><li><strong>Prompt Engineering</strong>: manage and structure prompts more effectively</li><li><strong>Chains</strong>: Combine multiple LLM calls or tools into sequences</li><li><strong>Memory</strong>: Supports stateful conversations — keeping context across multiple user inputs</li><li><strong>Data Connection</strong>: Integrates with sources like databases, APIs, or documents</li><li><strong>Agents</strong>: Supports dynamic decision-making workflows</li></ul><h3>Routers</h3><p>In simple terms, a device that forwards data packets to the appropriate parts of a computer network is called a router.</p><p>The primary functions of a router are</p><ul><li>managing traffic between these networks by forwarding data packets to their intended IP addresses</li><li>allowing multiple devices to use the same Internet connection</li></ul><h3>Why LangChain Routing?</h3><p>LangChain Routing is a powerful tool that helps make your LLM-powered application more intelligent, scalable, and efficient. It dynamically directs user queries to the most suitable model, chain, or tool based on the task, ensuring faster responses and reduces costs. This approach also keeps the application modular and easy to expand.</p><p><strong>Example:</strong></p><pre>&quot;Summarize this article&quot; → Summarizer chain<br><br>&quot;Translate this to French&quot; → Translator chain<br><br>&quot;What’s 25 * 7?&quot; → Calculator chain<br><br>Math questions → Calculator module<br><br>Text-based tasks → LLM<br><br>API data fetches → External API integration</pre><h3>Uses</h3><ul><li>Direct tasks to the right models/tools.</li><li>Balance cost &amp; performance.</li><li>Handle multiple domains/contexts.</li><li>Support multilingual interactions.</li><li>Build smarter, more flexible AI systems.</li></ul><h3>Use-case</h3><h4>Customer Support Bot</h4><p>Imagine you’re building a <strong>smart customer support assistant</strong> for an <strong>Insurance company.</strong></p><p>✅ <strong>Problem:</strong><br> Customers ask a variety of questions across different departments:</p><ul><li><strong>Claims:</strong> “How do I file a claim?”</li><li><strong>Underwriting:</strong> “What factors affect my premium?”</li><li><strong>Policy Details:</strong> “Can I add a family member to my policy?”</li><li><strong>Technical Issues:</strong> “I’m unable to access my account.”</li></ul><h4>Solution:</h4><p>Implementing different routers across different departments. For instance,</p><ul><li><strong>Claims: </strong>claims router</li><li><strong>Underwriting: </strong>UW router</li><li><strong>Policy details:</strong> General router (multi-purpose)</li><li><strong>Technical issues:</strong> Chatbot assistant router</li></ul><h3><strong>Simple Implementation</strong></h3><p>LangChain provides tools like RunnableLambda to create simple logic for picking different actions and chains.</p><p>Let’s look at a simple implementation of LangChain routing to increase our understanding about it.</p><pre># Installing libraries<br>!pip install langchain langchain_huggingface langchain_groq --q<br><br># imports<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.prompts import PromptTemplate<br>from langchain_groq import ChatGroq<br>from langchain_core.runnables import RunnableLambda</pre><p>Importing your API Keys</p><pre>import os<br>os.environ[&quot;GROQ_API_KEY&quot;] = &quot;&lt;your-api-key&gt;&quot;<br>os.environ[&quot;HF_TOKEN&quot;] = &quot;&lt;your-api-key&gt;&quot;</pre><h3>Choosing your LLM provider</h3><p>LangChain offers various chat models and it completely depends on your choice on choosing the provider.</p><h4>ChatGroq</h4><pre>llm = ChatGroq(<br>    #use the model of your wish<br>    model=&quot;llama-3.3-70b-versatile&quot;,<br>    temperature=0,<br>    max_tokens=None,<br>    timeout=None,<br>    max_retries=2,<br>    # other params...<br>)</pre><h4>ChatHuggingFace</h4><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br><br>hf_endpoint = HuggingFaceEndpoint(<br>    repo_id=&quot;&lt;model-id&gt;&quot;,<br>    task=&quot;text-generation&quot;,<br>    max_new_tokens=512,<br>    do_sample=False,<br>    # other params...<br>)<br><br>llm = ChatHuggingFace(llm=hf_endpoint)</pre><h3>Defining our PromptTemplate</h3><p><strong>Prompt Template</strong> is a flexible way to structure prompts for your language model. It allows you to define a prompt with placeholders (like variables), which get filled in dynamically when the prompt is used.</p><pre>prompt = PromptTemplate.from_template(&quot;&quot;&quot;<br>    Given the user question below, classify it as either being about <br>    `LangChain`, `HuggingFace`, or `Other`.<br>    Do not respond with more than one word.<br>    &lt;question&gt;<br>    {question}<br>    &lt;/question&gt;<br>    <br>    Classification:<br>    &quot;&quot;&quot;<br>)</pre><h3>Simple Chain Function</h3><p>The chain consists of 3 steps / processes:</p><ul><li><strong>prompt</strong> : Prompt template with placeholders filled.</li><li><strong>llm</strong> : our Chat models (ChatGroq / ChatHuggingFace).</li><li><strong>StrOutputParser</strong> : ensures the model’s output is parsed and returned as a clean string</li></ul><pre>chain = prompt | llm | StrOutputParser()</pre><h3>Invoking our chain</h3><p>Let’s invoke the chain with a simple prompt.</p><pre>ans = chain.invoke({&quot;question&quot;: &quot;How do I call HuggingFace?&quot;})<br>ans</pre><h4>Output</h4><pre>&#39;HuggingFace&#39;</pre><h3>Routing function (simple and straight-forward)</h3><p>We create a simple router function based on the outputs given by the chain function.</p><pre>def route(info):<br>    if &quot;huggingface&quot; in info[&quot;topic&quot;].lower():<br>        return huggingface_chain<br>    elif &quot;langchain&quot; in info[&quot;topic&quot;].lower():<br>        return langchain_chain<br>    else:<br>        return general_chain</pre><h3>Domain-based prompts and chains</h3><p>We customize the prompts based on the topics. The prompts are more or less similar.</p><pre>langchain_prompt = PromptTemplate.from_template(&quot;&quot;&quot;<br>  You are an expert in langchain. \<br>  Always answer questions starting with &quot;As Harrison Chase told me&quot;. \<br>  Respond to the following question:<br>  <br>  Question: {question}<br>  Answer:<br>  &quot;&quot;&quot;<br>)<br><br>huggingface_prompt = PromptTemplate.from_template(&quot;&quot;&quot;<br>  You are an expert in huggingface. \<br>  Always answer questions starting with &quot;As Dario Amodei told me&quot;. \<br>  Respond to the following question:<br>  <br>  Question: {question}<br>  Answer:<br>  &quot;&quot;&quot;<br>)<br><br>general_prompt = PromptTemplate.from_template(&quot;&quot;&quot;<br>  You are an expert in general knowledge and a big fan of Albert Einstein. \<br>  Always answer questions starting with &quot;As Einstein told me&quot;. \<br>  Respond to the following question:<br>  <br>  Question: {question}<br>  Answer:<br>  &quot;&quot;&quot;<br>)</pre><p>We chain the prompts to the LLMs (Chat Models).</p><pre>langchain_chain = langchain_prompt | llm<br>huggingface_chain = huggingface_prompt | llm<br>general_chain = general_prompt | llm</pre><h3>Complete Routing chain</h3><p>As discussed earlier, we use RunnableLambda to create simple logic for picking chains.</p><pre>full_chain = {&quot;topic&quot;: chain, &quot;question&quot;: lambda x: x[&quot;question&quot;]} <br>    | RunnableLambda(route)</pre><h3>Time to verify :)</h3><p>Let’s try and invoke the chain function with the same prompt.</p><pre>res = full_chain.invoke({&quot;question&quot;: &quot;How do I use huggingface?&quot;})<br>print(res.content)</pre><h3>Output</h3><pre>As Dario Amodei told me, to call Hugging Face, you don&#39;t actually &quot;call&quot; <br>them, but rather you can visit their website at https://huggingface.co/ <br>and explore their documentation, models, and community forums to get <br>started with their amazing library and tools. If you need support or have <br>questions, you can also reach out to them through their official channels, <br>such as GitHub, Twitter, or by attending one of their many community <br>events and meetups.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e379b054bbd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building our first simple GAN]]></title>
            <link>https://medium.com/@varunsivamani/building-our-first-simple-gan-5cef66988970?source=rss-4fae91d62ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cef66988970</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[generative-art]]></category>
            <dc:creator><![CDATA[Varun Sivamani]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 00:42:53 GMT</pubDate>
            <atom:updated>2024-06-04T00:42:53.201Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding basics of GAN</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/0*xRVZaEMtE29J1S-0.jpeg" /><figcaption>[<a href="https://paperswithcode.com/method/gan">Source</a>]</figcaption></figure><blockquote>The generator tries to fool the discriminator by generating real-looking images while the discriminator tries to distinguish between real and fake images.</blockquote><h3>Overview</h3><p>A generative adversarial network (GAN) has two parts:</p><ul><li>The <strong>generator</strong> learns to generate plausible data. The generated instances become negative training examples for the discriminator.</li><li>The <strong>discriminator</strong> learns to distinguish the generator’s fake data from real data. The discriminator penalizes the generator for producing implausible results.</li></ul><p>When training begins, the generator produces obviously fake data, and the discriminator quickly learns to tell that it’s fake.</p><h3>Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*AjzwaegHm2LW362qP3AQaw.png" /><figcaption>[<a href="https://arxiv.org/pdf/1406.2661v1">Source</a>]</figcaption></figure><h3>Discriminator Model</h3><p>The discriminator model takes an example from the domain as input (real or generated) and predicts a binary class label of real or fake (generated).</p><ul><li>The real example comes from the training dataset. The generated examples are output by the generator model.</li><li>The discriminator is a normal (and well understood) classification model.</li><li>After the training process, the discriminator model is discarded as we are interested in the generator.</li></ul><p>Sometimes, the generator can be repurposed as it has learned to effectively extract features from examples in the problem domain. Some or all of the feature extraction layers can be used in transfer learning applications using the same or similar input data.</p><pre>class Discriminator(nn.Module):<br>    def __init__(self, in_features):<br>        super().__init__()<br>        self.disc = nn.Sequential(<br>            nn.Linear(in_features, 128),<br>            nn.LeakyReLU(0.01),<br>            nn.Linear(128, 1),<br>            nn.Sigmoid(),<br>        )<br><br>    def forward(self, x):<br>        return self.disc(x)</pre><h3>Generator Model</h3><p>The generator model takes a fixed-length random vector as input to generate samples in a specific domain. The vector is drawn from randomly from a Gaussian distribution, and the vector is used to seed the generative process. This vector space is known as a latent space, composed of latent variables.</p><p>A latent space provides a compressed or high-level representation of the observed raw data, such as the input data distribution.</p><p>The generator model applies meaning to points in a chosen latent space, such that new points drawn from the latent space can be provided to the generator model as input and used to generate new and different output examples. After training, the generator model is retained and used to generate new samples.</p><pre>class Generator(nn.Module):<br>    def __init__(self, z_dim, img_dim):<br>        super().__init__()<br>        self.gen = nn.Sequential(<br>            nn.Linear(z_dim, 256),<br>            nn.LeakyReLU(0.01),<br>            nn.Linear(256, img_dim),<br>            nn.Tanh(),  <br>            # normalize inputs to [-1, 1] so make outputs [-1, 1]<br>        )<br><br>    def forward(self, x):<br>        return self.gen(x)</pre><h3>Building our simple GAN</h3><p>Let’s build a simple GAN model using <strong>MNIST</strong> dataset.</p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import torchvision<br>import torchvision.datasets as datasets<br>from torch.utils.data import DataLoader<br>import torchvision.transforms as transforms<br>from torch.utils.tensorboard import SummaryWriter  # print to tensorboard<br><br># Hyperparameters<br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>lr = 3e-4<br>z_dim = 64<br>image_dim = 28 * 28 * 1  # 784<br>batch_size = 32<br>num_epochs = 50<br><br>disc = Discriminator(image_dim).to(device)<br>gen = Generator(z_dim, image_dim).to(device)<br>fixed_noise = torch.randn((batch_size, z_dim)).to(device)<br>transforms = transforms.Compose(<br>    [<br>        transforms.ToTensor(),<br>        transforms.Normalize((0.5,), (0.5,)),<br>    ]<br>)<br><br>dataset = datasets.MNIST(root=&quot;data/&quot;, transform=transforms, download=True)<br>loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)<br>opt_disc = optim.Adam(disc.parameters(), lr=lr)<br>opt_gen = optim.Adam(gen.parameters(), lr=lr)<br>criterion = nn.BCELoss()<br>writer_fake = SummaryWriter(f&quot;logs/fake&quot;)<br>writer_real = SummaryWriter(f&quot;logs/real&quot;)</pre><h3>Training our simple GAN</h3><p>We will train our GAN model and plot the fake images generated along with the real images.</p><p>The generator and discriminator are trained in a loop:</p><ol><li>The generator creates fake data samples from noise.</li><li>The discriminator evaluates these samples along with real samples from the dataset.</li><li>The discriminator’s feedback (whether it thinks the samples are real or fake) is used to calculate the loss.</li><li>The generator updates its parameters to minimize this loss, effectively improving its capability to generate realistic data that can fool the discriminator.</li></ol><pre>step = 0<br><br>for epoch in range(num_epochs):<br>    for batch_idx, (real, _) in enumerate(loader):<br>        real = real.view(-1, 784).to(device)<br>        batch_size = real.shape[0]<br><br>        ### Train Discriminator: max log(D(x)) + log(1 - D(G(z)))<br>        noise = torch.randn(batch_size, z_dim).to(device)<br>        fake = gen(noise)<br>        disc_real = disc(real).view(-1)<br>        lossD_real = criterion(disc_real, torch.ones_like(disc_real))<br>        disc_fake = disc(fake).view(-1)<br>        lossD_fake = criterion(disc_fake, torch.zeros_like(disc_fake))<br>        lossD = (lossD_real + lossD_fake) / 2<br>        disc.zero_grad()<br>        lossD.backward(retain_graph=True)<br>        opt_disc.step()<br><br>        ### Train Generator: min log(1 - D(G(z))) &lt;-&gt; max log(D(G(z))<br>        # where the second option of maximizing doesn&#39;t suffer from<br>        # saturating gradients<br>        output = disc(fake).view(-1)<br>        lossG = criterion(output, torch.ones_like(output))<br>        gen.zero_grad()<br>        lossG.backward()<br>        opt_gen.step()<br><br>        if batch_idx == 0:<br>            print(<br>                f&quot;Epoch [{epoch}/{num_epochs}] \<br>                  Batch {batch_idx}/{len(loader)} \<br>                  Loss D: {lossD:.4f}, loss G: {lossG:.4f}&quot;<br>            )<br><br>            with torch.no_grad():<br>                fake = gen(fixed_noise).reshape(-1, 1, 28, 28)<br>                data = real.reshape(-1, 1, 28, 28)<br>                img_grid_fake = torchvision.utils.make_grid(<br>                                    fake, normalize=True<br>                                )<br>                img_grid_real = torchvision.utils.make_grid(<br>                                    data, normalize=True<br>                                )<br><br>                writer_fake.add_image(<br>                    &quot;Mnist Fake Images&quot;, img_grid_fake, global_step=step<br>                )<br>                writer_real.add_image(<br>                    &quot;Mnist Real Images&quot;, img_grid_real, global_step=step<br>                )<br>                step += 1</pre><h3>Applications</h3><ol><li><strong>Image Generation and Enhancement:</strong> Generating high-quality synthetic images and improving image resolution.</li><li><strong>Data Augmentation:</strong> Creating additional training data to improve machine learning model performance.</li><li><strong>Video and Animation: </strong>Producing realistic videos and animations for entertainment and simulation.</li><li><strong>Healthcare: </strong>Synthesizing medical images to aid in research and diagnostic tool development.</li><li><strong>Text-to-Image Synthesis:</strong> Generating images from textual descriptions for creative and design purposes.</li><li><strong>Style Transfer and Artistic Creation:</strong> Applying artistic styles to images and generating artwork.</li></ol><h3>Conclusion</h3><p>GANs have significantly impacted the field of artificial intelligence with their ability to generate realistic and high-quality synthetic data. Their applications range from image and video generation to healthcare, fashion, gaming, and beyond. While they offer immense potential for innovation and practical use, it is also important to address the ethical and security concerns they raise. As research and development in GANs continue, their influence and utility are set to expand even further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cef66988970" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto-Encoders and VAE]]></title>
            <link>https://medium.com/@varunsivamani/auto-encoders-and-vae-e9d496e40477?source=rss-4fae91d62ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9d496e40477</guid>
            <category><![CDATA[encoder]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Varun Sivamani]]></dc:creator>
            <pubDate>Tue, 28 May 2024 00:42:21 GMT</pubDate>
            <atom:updated>2024-05-28T04:56:55.173Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring Auto-encoders and Variational Auto-encoders</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*Fnnjbl1TEkN8QkQSlQAqWA.png" /></figure><h3>What are Auto-Encoders?</h3><p>Autoencoders are a type of neural network architecture used for unsupervised learning, where the goal is to learn a compressed representation (encoding) of the input data.</p><p>The basic idea is to learn a function that maps the input data to a lower-dimensional representation and then reconstructs the original data from the encoded representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zUB81D6msoDdtjse.png" /></figure><h4>Objectives</h4><p>The primary goal of an autoencoder is to learn a compact representation of the input data by <strong>minimizing the reconstruction error</strong>. This error quantifies how accurately the autoencoder can reproduce the original input from the compressed latent representation. Minimizing this error ensures that the latent space captures the most significant features of the input data.</p><h3>What about Variational Auto-Encoders?</h3><p>Variational Autoencoders have one fundamentally unique property that separates them from vanilla autoencoders, and it is this property that makes them so useful for generative modeling: <strong>their latent spaces are, by design, continuous</strong>, allowing easy random sampling and interpolation.</p><p>It achieves this by doing something that seems rather surprising at first: making its encoder <strong>NOT</strong> output an encoding vector of size n, but rather, outputting two vectors of size n: <strong>a vector of means μ, and another vector of standard deviations σ</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*4p2NWahKF7kZnI29Wt4-7g.png" /></figure><p>So the encoder predicts two kinds of vectors, mean and std. When now we send data to the decoder we sample from this mean and std!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*RdkjfoVMD8YBCeRAWYJTPQ.png" /></figure><p>Even for the same input, while the mean and standard deviations remain the same, the actual encoding will somewhat vary on every single pass, simply due to <strong>sampling.</strong></p><blockquote>VAE Loss = Reconstruction Loss + KL Divergence</blockquote><h3><strong>Kullback-Leibler Divergence (KL)</strong></h3><p>KL divergence is the measure of the relative difference between two probability distributions for a given random variable or set of events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*jxloFeInB4DL_t2f6rJH5g.png" /></figure><ul><li>X is a possible event in the probability space.</li><li>P(x) and Q(x) are the probabilities of x in the distribution of P and Q, respectively.</li><li>The ratio P(x)/Q(x) represents the relative likelihood of event “x” according to P compared to Q.</li></ul><h4>Limitations</h4><ul><li>KL divergence is an <strong>asymmetric metric</strong>. This means that it can not be used as strictly a distance measure since the distance between two entities remains the same from either perspective.</li><li>If the data samples are pulled from distributions that use different parameters (mean and variance), KL divergence will not yield reliable results. In this case, one of the distributions needs to be adjusted to match the other.</li></ul><h3><strong>Coding an Auto-Encoder model</strong></h3><p>Let us look at a simple auto-encoder architecture for MNIST dataset.</p><pre>class Autoencoder(nn.Module):<br>    def __init__(self, latent_dims):<br>        super(Autoencoder, self).__init__()<br>        self.encoder = Encoder(latent_dims)<br>        self.decoder = Decoder(latent_dims)<br><br>    def forward(self, x):<br>        z = self.encoder(x)<br>        return self.decoder(z)</pre><p>The Encoder and Decoder architectures are,</p><pre>class Encoder(nn.Module):<br>    def __init__(self, latent_dims):<br>        super(Encoder, self).__init__()<br>        self.linear1 = nn.Linear(784, 512)<br>        self.linear2 = nn.Linear(512, latent_dims)<br><br>    def forward(self, x):<br>        x = torch.flatten(x, start_dim=1)<br>        x = F.relu(self.linear1(x))<br>        return self.linear2(x)<br><br><br>class Decoder(nn.Module):<br>    def __init__(self, latent_dims):<br>        super(Decoder, self).__init__()<br>        self.linear1 = nn.Linear(latent_dims, 512)<br>        self.linear2 = nn.Linear(512, 784)<br><br>    def forward(self, z):<br>        z = F.relu(self.linear1(z))<br>        z = torch.sigmoid(self.linear2(z))<br>        return z.reshape((-1, 1, 28, 28))</pre><h4>Training function</h4><pre>def train(autoencoder, data, epochs=20):<br>    opt = torch.optim.Adam(autoencoder.parameters())<br>    for epoch in range(epochs):<br>        for x, y in data:<br>            x = x.to(device) # GPU<br>            opt.zero_grad()<br>            x_hat = autoencoder(x)<br>            loss = ((x - x_hat)**2).sum()<br>            loss.backward()<br>            opt.step()<br>    return autoencoder</pre><h3>Coding a Variational Auto-Encoder model</h3><pre>class VariationalAutoencoder(nn.Module):<br>    def __init__(self, latent_dims):<br>        super(VariationalAutoencoder, self).__init__()<br>        self.encoder = VariationalEncoder(latent_dims)<br>        self.decoder = Decoder(latent_dims)<br><br>    def forward(self, x):<br>        z = self.encoder(x)<br>        return self.decoder(z)</pre><p>We will use the same decoder from Auto-encoders and construct a new encoder.</p><pre>class VariationalEncoder(nn.Module):<br>    def __init__(self, latent_dims):<br>        super(VariationalEncoder, self).__init__()<br>        self.linear1 = nn.Linear(784, 512)<br>        self.linear2 = nn.Linear(512, latent_dims)<br>        self.linear3 = nn.Linear(512, latent_dims)<br><br>        self.N = torch.distributions.Normal(0, 1)<br>        self.N.loc = self.N.loc.cuda() # hack to get sampling on the GPU<br>        self.N.scale = self.N.scale.cuda()<br>        self.kl = 0<br><br>    def forward(self, x):<br>        x = torch.flatten(x, start_dim=1)<br>        x = F.relu(self.linear1(x))<br>        mu =  self.linear2(x)<br>        sigma = torch.exp(self.linear3(x))<br>        z = mu + sigma*self.N.sample(mu.shape)<br>        self.kl = (sigma**2 + mu**2 - torch.log(sigma) - 1/2).sum()<br>        return z</pre><h4>Training function</h4><pre>def train(autoencoder, data, epochs=20):<br>    opt = torch.optim.Adam(autoencoder.parameters())<br>    for epoch in range(epochs):<br>        for x, y in data:<br>            x = x.to(device) # GPU<br>            opt.zero_grad()<br>            x_hat = autoencoder(x)<br>            loss = ((x - x_hat)**2).sum() + autoencoder.encoder.kl<br>            loss.backward()<br>            opt.step()<br>    return autoencoder</pre><h3>Conclusion</h3><p>VAEs provide a more flexible and generative approach due to their probabilistic nature. This makes VAEs more suitable for tasks requiring data generation and handling uncertainty, whereas traditional autoencoders are often preferred for tasks focused on efficient data representation and reconstruction. Both models have significantly contributed to advancements in machine learning and continue to be fundamental tools in the development of more sophisticated neural network architectures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9d496e40477" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speeding-up Transformers ️ → ]]></title>
            <link>https://medium.com/@varunsivamani/speeding-up-transformers-%EF%B8%8F-c9cfbdd6ef27?source=rss-4fae91d62ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9cfbdd6ef27</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Varun Sivamani]]></dc:creator>
            <pubDate>Sat, 25 May 2024 14:41:33 GMT</pubDate>
            <atom:updated>2026-09-08T09:19:39.995Z</atom:updated>
            <content:encoded><![CDATA[<p>Optimizing Transformer architecture for faster inferences 🏁🏆</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*uH30inTR8l2TVO1N.jpg" /></figure><p>Training state-of-the-art (SOTA) models necessitates the use of GPUs. While services like <strong>Google Colab or Kaggle</strong> offer access to GPUs, they often come with memory constraints. It’s common to encounter Out of Memory (OOM) or GPU Runtime Limit Reached errors when using large batches, extensive models, or prolonged epochs.</p><p>This notebook explores various optimization strategies to address these issues, providing in-depth analysis and code examples.</p><h3>Problem</h3><p>The issue is particularly pronounced with transformers, known for their high memory consumption. Training larger models or extending epochs increases the likelihood of running out of memory or exceeding runtime limits.</p><p>For example, in certain competitions, loss can be oscillating or unstable. To identify the best-performing models, it is often necessary to evaluate more frequently within each epoch rather than just at the end, which is resource-intensive and can lead to GPU Runtime Limit Reached errors, especially when training in folds.</p><h3>Solution</h3><p>Several well-known, out-of-the-box strategies can help mitigate these issues, each offering distinct advantages:</p><ul><li><strong><em>Dynamic Padding and Uniform Length Batching</em></strong></li><li><strong><em>Numeric Precision Reduction</em></strong></li><li><strong><em>Parameter Sharing</em></strong></li><li><strong><em>Freezing Embeddings</em></strong></li><li><strong><em>Gradient Accumulation</em></strong></li><li><strong><em>Gradient Checkpointing</em></strong></li></ul><h3>Dynamic Padding</h3><p>In this method, we limit the number of padding tokens added to match the length of the longest sequence in each mini-batch, rather than using a fixed value for the entire training set. Since the number of padding tokens varies across mini-batches, this method is termed “dynamic padding”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0S0okl_aw4Rh-xNKYfuxg.png" /><figcaption>Adding [PAD] sequences dynamically according to largest sequence length</figcaption></figure><h3>Uniform Length Batching</h3><p>In this method, we generate batches made of similar length sequences so we avoid extreme cases where most sequences in the mini batch are short and we are required to add lots of pad tokens to each of them because 1 sequence of the same mini batch is very long.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNg0S6edIHqha9YA91nAAA.png" /><figcaption>Dynamic padding according to batch sequence length</figcaption></figure><h3>Numeric Precision Reduction</h3><p>Numeric precision reduction involves speeding up computations through floating point reduction and quantization. This is one of the most general methods for achieving prediction-time speedups. Previously, poor support for float16 operations on GPU hardware often made reducing the precision of weights and activations counterproductive. However, the advent of NVIDIA’s Volta and Turing architectures with Tensor Cores means that modern GPUs are now well-suited for efficient float16 arithmetic.</p><h4>Floating Point Representation</h4><p>Floating point types store numeric information in three parts: the sign, exponent, and fraction. Traditional float32 representations use 8 bits for the exponent and 23 bits for the fraction. Traditional float16 representations, used by NVIDIA hardware, roughly halve the bits allocated to both the exponent and the fraction. TPUs use a variant called bfloat16. Most of a transformer network can be converted to float16 weights and activations without any loss in accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/0*vSDpXS6XK4zBxC3x.png" /><figcaption>Floating Point Representation</figcaption></figure><h4>Mixed Precision Training</h4><p>Instances of torch.cuda.amp.autocast (or torch.autocast) serve as context managers that allow regions of your script to run in mixed precision. Matrix Multiplication and convolutions are moved to F16 calculations, and backprop is still kept at F32.</p><pre># Create model and optimizer in default precision<br>model = .... # your model<br>optimizer = .... # your optimizer of choice<br><br>for input, target in data:<br>    optimizer.zero_grad()<br><br>    # Enables autocasting for the forward pass (model + loss)<br>    with torch.autocast(device_type=&quot;cuda&quot;):<br>        output = model(input)<br>        loss = loss_fn(output, target)<br><br>    # Exits the context manager before backward()<br>    loss.backward()<br>    optimizer.step()</pre><h3>Parameter Sharing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*hXSkaUWrEx8Ue9LB0O3ovQ.png" /><figcaption>[<a href="https://arxiv.org/pdf/2104.06022">Source</a>]</figcaption></figure><p>Parameter sharing in transformers is a technique used to reduce the number of parameters in a model by reusing the same parameters across multiple layers. This approach can help mitigate the memory and computational overhead of deep transformer models, making them more efficient while maintaining their performance.</p><h3>Freeze Embedding</h3><p>Freezing the embedding matrix during the fine-tuning of a pre-trained language model is a straightforward yet effective technique. By freezing the embedding layer of transformers, you can save GPU memory, allowing for larger batch sizes during training. This approach also accelerates the training process.</p><p>Let us look at a common example:</p><pre>from transformers import TFAutoModelForCausalLM<br>model = TFAutoModelForCausalLM.from_pretrained(&#39;gpt2&#39;)<br>model.transformer.wte.trainable=False  # Freeze embeddings<br>model.compile()<br>model.summary()</pre><h3>Gradient Accumulation</h3><p>Gradient accumulation is a technique used to manage and optimize the use of computational resources, particularly when dealing with limited GPU memory. It allows the effective batch size to be larger than what can be processed in one forward and backward pass by accumulating gradients over multiple smaller mini-batches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*-OG5cWBYccmRlMrk.png" /></figure><p>The core idea behind gradient accumulation is to accumulate the gradients from several smaller mini-batches instead of updating the model parameters after each mini-batch. This approach effectively simulates a larger batch size without requiring the memory to store all samples at once.</p><h3>How It Works</h3><ol><li><strong>Mini-Batch Processing:</strong> Instead of computing the gradient and updating the model parameters after each mini-batch, gradients are accumulated over several mini-batches.</li><li><strong>Accumulation Steps:</strong> After a predefined number of mini-batches (let’s say N), the accumulated gradients are used to update the model parameters. This makes the effective batch size equal to the size of the mini-batch multiplied by N.</li><li><strong>Gradient Update:</strong> Once the accumulation steps are complete, the optimizer updates the model parameters using the accumulated gradients, and then the gradients are reset for the next set of mini-batches.</li></ol><h3>Gradient Checkpointing</h3><p>Gradient checkpointing is a technique used to reduce the memory footprint when training deep neural networks, with a slight increase in computation time. This method trades compute resources for memory savings, allowing for the training of larger or wider models and the use of larger mini-batch sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/0*RBIdZylnj-uAP7rb" /></figure><p>The core idea is to perform backpropagation in smaller chunks along the model. Instead of storing the entire backpropagation graph in memory, gradient checkpointing saves memory by recalculating intermediate activations during the backward pass.</p><p>This involves additional forward passes for each chunk, resulting in increased computation but significantly reduced memory usage. Although this method slows down training due to the extra computations, it enables the use of larger batch sizes and can be particularly beneficial in certain scenarios.</p><h3>Conclusion</h3><p>Speeding up transformers is a complex yet promising field with several more strategies evolving and improving from time-to-time. These approaches, when carefully implemented, can significantly reduce computational costs and inference time while maintaining or even improving model performance.</p><p>Ultimately, as transformers continue to evolve and improve in speed and efficiency, they tend to produce increasingly remarkable and inspiring results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9cfbdd6ef27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ViT : Vision Transformer]]></title>
            <link>https://medium.com/@varunsivamani/vit-vision-transformer-58dad036ee12?source=rss-4fae91d62ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/58dad036ee12</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[self-attention-mechanism]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[vision-transformer]]></category>
            <dc:creator><![CDATA[Varun Sivamani]]></dc:creator>
            <pubDate>Wed, 22 May 2024 18:37:30 GMT</pubDate>
            <atom:updated>2024-05-22T18:37:30.853Z</atom:updated>
            <content:encoded><![CDATA[<h3>ViT : Vision Transformer</h3><p>An Image 📸 is worth 16x16 Words</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgCRzLwhW6JCszC_VFXNKg.png" /></figure><p>Vision Transformer (ViT) was introduced by the <strong>Brain Team, Google Research</strong>,<strong> </strong>in the paper, “<a href="https://arxiv.org/abs/2010.11929"><em>An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale</em></a><em>”. </em>It’s the first paper that successfully trains a Transformer encoder on ImageNet, attaining very good results compared to familiar convolutional architectures.</p><blockquote>Inspired by the Transformer scaling successes in NLP, we experiment with applying a standard Transformer directly to images, with the fewest possible modifications. To do so, we split an image into patches and provide the sequence of linear embeddings of these patches as an input to a Transformer. Image patches are treated the same way as tokens (words) in an NLP application. We train the model on image classification in supervised fashion.</blockquote><blockquote><strong>-Authors</strong></blockquote><h3>ViT Model Variants</h3><p>The “Base” and “Large” models are directly adopted from BERT and we add the larger “Huge” model. For instance, ViT-L/16 means the “Large” variant with 16×16 input patch size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*faCLA7vOSTGsJ588EnQWkg.png" /><figcaption>ViT variants</figcaption></figure><blockquote>Note: The Transformer’s sequence length is inversely proportional to the square of the patch size, thus models with smaller patch size are computationally more expensive.</blockquote><h3>How is ViT better than CNN?</h3><ol><li><strong>Global context: </strong>ViTs capture global dependencies in the image by treating the image as a sequence of patches. Each patch is embedded and processed by the transformer layers, allowing ViTs to potentially model long-range dependencies more effectively than CNNs, which typically use local receptive fields.</li><li><strong>Fewer parameters for large images:</strong> ViTs can handle high-resolution images more efficiently than CNNs. Since ViTs process images as sequences of patches, they require fewer parameters compared to CNNs, which need to process the entire image at once.</li><li><strong>Data efficiency:</strong> ViTs might be more data-efficient than CNNs for some tasks. The attention mechanism in ViTs allows them to learn from different parts of the image more selectively, potentially requiring less data to achieve good performance.</li><li><strong>Transfer learning: </strong>ViTs trained on large-scale datasets like ImageNet have shown strong performance on various downstream tasks with minimal fine-tuning. Their ability to capture rich image features in a self-supervised manner during pretraining can be advantageous in transfer learning scenarios.</li><li><strong>Interpretable representations:</strong> The attention mechanism in ViTs allows for more interpretable feature representations. For example, it’s easier to visualize which parts of the image are attended to for a specific output, providing insights into the model’s decision-making process.</li></ol><h3>How does ViT work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*Kbg8INDZDb9RgBFQ.png" /><figcaption>Vision Transformer Architecture</figcaption></figure><p><strong>1. Patch Embedding</strong></p><ul><li>The input image is divided into fixed-size patches, typically 16x16 pixels.</li><li>Each patch is then linearly projected into a lower-dimensional space to create patch embeddings.</li><li>These embeddings capture the content of each patch and serve as input tokens for the transformer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*ogvjQTBQ5WYBIG-SLVI4TA.png" /><figcaption>Filters of the initial linear embedding of RGB values of ViT-L/32 [<a href="https://arxiv.org/pdf/2010.11929">Source</a>]</figcaption></figure><p><strong>2. Positional Embedding</strong></p><ul><li>Since transformers do not inherently understand the spatial relationships between tokens, positional embeddings are added to the patch embeddings.</li><li>Positional embeddings provide information about the position of each patch in the original image, allowing the model to learn spatial relationships.</li><li>These embeddings are typically learned or predefined.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*uOAzMu4jWL8bNiF6CSCokQ.png" /><figcaption>Similarity of position embeddings of ViT-L/32 (cosine similarity) [<a href="https://arxiv.org/pdf/2010.11929">Source</a>]</figcaption></figure><p><strong>3. Encoder Layers</strong></p><ul><li>The transformer encoder consists of multiple identical layers, each comprising two main components: multi-head self-attention and feedforward neural networks.</li><li>The encoder processes the patch embeddings and positional embeddings sequentially, with each layer refining the representation of the image.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*Txe98-VcpLmTNJJ2eydRvA.jpeg" /><figcaption>Encoder block</figcaption></figure><p><strong>4. Multi-Head Self-Attention</strong></p><ul><li>Self-attention allows the model to weigh the importance of different patches when processing each patch.</li><li>Multi-head self-attention further enhances this mechanism by allowing the model to focus on different parts of the image simultaneously, capturing both local and global dependencies effectively.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*l4HwfEqFEDk7WrLWi9E0tg.png" /><figcaption>Examples of attention from the output token to the input space. [<a href="https://arxiv.org/pdf/2010.11929">Source</a>]</figcaption></figure><p><strong>5. Feedforward Neural Networks</strong></p><ul><li>After self-attention, the output is passed through a feedforward neural network (FNN) for further processing.</li><li>The FNN consists of two linear transformations with a non-linear activation function (such as ReLU) in between, enabling the model to learn complex relationships between patches.</li></ul><p><strong>6. Layer Normalization and Residual Connections</strong></p><ul><li>Layer normalization is applied after each sub-layer (self-attention and FNN) to stabilize training.</li><li>Residual connections, where the input to a layer is added to its output, are also used to facilitate the flow of gradients during training and improve the model’s ability to learn.</li></ul><h3><strong>Limitations</strong></h3><ol><li><strong>Computational Complexity:</strong> ViTs can be computationally expensive, especially for high-resolution images. Processing each patch individually and computing self-attention across all patches can lead to high memory and computation requirements.</li><li><strong>Attention Mechanism Overhead:</strong> The self-attention mechanism introduces a quadratic dependency on the input sequence length (number of patches). This can make ViTs less scalable to very large images or long sequences, as the computational cost of self-attention grows quadratically with the sequence length.</li><li><strong>Limited Spatial Understanding: </strong>While ViTs can capture global dependencies in images, they may struggle with capturing detailed spatial information at fine scales. This is because the spatial resolution of the patches is relatively coarse, and the positional encodings may not fully capture fine-grained spatial relationships.</li><li><strong>Data Efficiency:</strong> Training ViTs from scratch on small datasets can be challenging due to their large number of parameters and the need for large-scale data for effective pretraining. Fine-tuning pretrained ViTs on smaller datasets is more common, but this may limit their generalization to new or diverse datasets.</li></ol><h3>Conclusion</h3><p>The Vision Transformer architecture processes data in a versatile manner, enabling it to extract information from various parts or pixels of an image. This is achieved by utilizing self-attention mechanisms, which help capture relationships within the image’s overall context. Additionally, researchers have explored combining both Convolutional Neural Networks (CNNs) and Vision Transformers (ViTs) to create hybrid architectures, resulting in exceptional performance.</p><h3>References</h3><ul><li><a href="https://arxiv.org/abs/2010.11929v2">https://arxiv.org/abs/2010.11929v2</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58dad036ee12" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>