<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: transformers</title>
    <description>The latest articles tagged 'transformers' on DEV Community.</description>
    <link>https://dev.to/t/transformers</link>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/tag/transformers"/>
    <language>en</language>
    <item>
      <title>Top Dev Tools and Tutorials: QuantumAI, NeuroSync, and More for 2026</title>
      <dc:creator>karleeov</dc:creator>
      <pubDate>Thu, 13 Aug 2026 23:03:54 +0000</pubDate>
      <link>https://dev.to/karleeov/top-dev-tools-and-tutorials-quantumai-neurosync-and-more-for-2026-2e88</link>
      <guid>https://dev.to/karleeov/top-dev-tools-and-tutorials-quantumai-neurosync-and-more-for-2026-2e88</guid>
      <description>&lt;h2&gt;
  
  
  QuantumAI SDK v2.0
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What it is
&lt;/h3&gt;

&lt;p&gt;QuantumAI SDK v2.0 is a toolkit for developing and deploying quantum machine learning applications. It offers enhanced features and easier hardware integration.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why now
&lt;/h3&gt;

&lt;p&gt;The release of v2.0 introduces significant improvements in error correction and new APIs, making quantum computing more accessible to mainstream developers.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tutorial angle
&lt;/h3&gt;

&lt;p&gt;Learn how to set up a quantum machine learning model using the new APIs, implement error correction, and deploy it on quantum hardware.&lt;/p&gt;

&lt;h3&gt;
  
  
  Difficulty
&lt;/h3&gt;

&lt;p&gt;Intermediate&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Start today:&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install &lt;/span&gt;quantumai-sdk&lt;span class="o"&gt;==&lt;/span&gt;2.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  NeuroSync CLI v1.5
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What it is
&lt;/h3&gt;

&lt;p&gt;NeuroSync CLI v1.5 is a command-line interface for managing and synchronizing neural networks across multiple devices in real-time.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why now
&lt;/h3&gt;

&lt;p&gt;The update adds real-time synchronization, crucial for the growing demand in distributed AI applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tutorial angle
&lt;/h3&gt;

&lt;p&gt;Discover how to set up and manage a distributed AI model using NeuroSync CLI's real-time synchronization features.&lt;/p&gt;

&lt;h3&gt;
  
  
  Difficulty
&lt;/h3&gt;

&lt;p&gt;Intermediate&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Start today:&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-g&lt;/span&gt; neurosync-cli
neurosync init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  TensorFlow Quantum 1.3
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What it is
&lt;/h3&gt;

&lt;p&gt;TensorFlow Quantum 1.3 is an extension of TensorFlow for building and experimenting with hybrid quantum-classical machine learning models.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why now
&lt;/h3&gt;

&lt;p&gt;Enhanced simulators and hybrid model support make it ideal for developers to explore quantum algorithms within TensorFlow.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tutorial angle
&lt;/h3&gt;

&lt;p&gt;Follow a step-by-step guide on integrating hybrid quantum-classical models into existing TensorFlow workflows.&lt;/p&gt;

&lt;h3&gt;
  
  
  Difficulty
&lt;/h3&gt;

&lt;p&gt;Intermediate&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Start today:&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;pip&lt;/span&gt; &lt;span class="n"&gt;install&lt;/span&gt; &lt;span class="n"&gt;tensorflow&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;quantum&lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="mf"&gt;1.3&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  PyTorch Lightning v2.0
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What it is
&lt;/h3&gt;

&lt;p&gt;PyTorch Lightning v2.0 is a lightweight PyTorch wrapper that simplifies the process of building scalable AI models with a modular architecture.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why now
&lt;/h3&gt;

&lt;p&gt;The new modular architecture and pre-built modules streamline complex AI model development, aligning with the trend of rapid AI innovation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tutorial angle
&lt;/h3&gt;

&lt;p&gt;Build a scalable AI model using PyTorch Lightning's modular components and multi-node training features.&lt;/p&gt;

&lt;h3&gt;
  
  
  Difficulty
&lt;/h3&gt;

&lt;p&gt;Intermediate&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Start today:&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install &lt;/span&gt;pytorch-lightning&lt;span class="o"&gt;==&lt;/span&gt;2.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Hugging Face Transformers v5.0
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What it is
&lt;/h3&gt;

&lt;p&gt;Hugging Face Transformers v5.0 is a library for natural language processing tasks, featuring pre-trained models and tools for multi-lingual AI applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why now
&lt;/h3&gt;

&lt;p&gt;The release introduces new pre-trained models and enhanced multi-lingual support, catering to the increasing demand for global AI solutions.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tutorial angle
&lt;/h3&gt;

&lt;p&gt;Leverage the new pre-trained models and tools for deploying multi-lingual AI applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  Difficulty
&lt;/h3&gt;

&lt;p&gt;Beginner&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Start today:&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install &lt;/span&gt;&lt;span class="nv"&gt;transformers&lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;5.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Building in public: my lead-gen engine
&lt;/h2&gt;

&lt;p&gt;My lead-gen engine has been actively discovering and enriching leads in the Hong Kong SME sector. Recent regional events like "Super Typhoon Dolphin" and "Flood in China" have underscored the importance of business continuity and digital backups. Here are the pipeline totals:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Discovered leads: 610&lt;/li&gt;
&lt;li&gt;Enriched leads: 388&lt;/li&gt;
&lt;li&gt;Contacted leads: 430&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Key insights:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Focus on tools that enhance business continuity and digital resilience.&lt;/li&gt;
&lt;li&gt;Increased interest in AI and machine learning solutions for disaster response.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Start with this today
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Hugging Face Transformers v5.0&lt;/strong&gt; is a great starting point for anyone interested in multi-lingual AI applications. To get started, run the following command to install the library:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install &lt;/span&gt;&lt;span class="nv"&gt;transformers&lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;5.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Picks of the week
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;QuantumAI SDK v2.0&lt;/strong&gt;: Ideal for developers looking to explore quantum machine learning.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;NeuroSync CLI v1.5&lt;/strong&gt;: Perfect for managing distributed AI models with real-time synchronization.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Hugging Face Transformers v5.0&lt;/strong&gt;: Best for multi-lingual AI applications.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What are your thoughts on the latest trends in quantum computing and AI? Share your insights in the comments below!&lt;/p&gt;




&lt;h4&gt;
  
  
  Connect
&lt;/h4&gt;

&lt;p&gt;If this kind of post is useful, the easiest way to support the work is to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Star / follow&lt;/strong&gt; on &lt;a href="https://dev.to/karleeov"&gt;dev.to&lt;/a&gt; (you're already here 🙂)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Follow on X&lt;/strong&gt;: &lt;a href="https://x.com/devkingov" rel="noopener noreferrer"&gt;@devkingov&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reach out for HK-based dev work&lt;/strong&gt; — .NET / Azure / system integration / IT security: &lt;a href="https://studio.resurrects.co" rel="noopener noreferrer"&gt;studio.resurrects.co&lt;/a&gt; or email &lt;a href="mailto:devkingov@gmail.com"&gt;devkingov@gmail.com&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Subscribe to weekly HK tech posts&lt;/strong&gt; → &lt;a href="https://studio.resurrects.co/blog" rel="noopener noreferrer"&gt;studio.resurrects.co/blog&lt;/a&gt; (one email a week, no spam)&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>quantumai</category>
      <category>tensorflow</category>
      <category>pytorch</category>
      <category>transformers</category>
    </item>
    <item>
      <title>Part 2: Comparing AI Frameworks for Natural Language Processing: Transformers and Recurrent Neural Networks</title>
      <dc:creator>Vijay Vinoth</dc:creator>
      <pubDate>Wed, 12 Aug 2026 04:17:13 +0000</pubDate>
      <link>https://dev.to/vijay_vinoth_8e7abfd3f5b5/part-2-comparing-ai-frameworks-for-natural-language-processing-transformers-and-recurrent-neural-3fk6</link>
      <guid>https://dev.to/vijay_vinoth_8e7abfd3f5b5/part-2-comparing-ai-frameworks-for-natural-language-processing-transformers-and-recurrent-neural-3fk6</guid>
      <description>&lt;h2&gt;
  
  
  Part 2: Comparing AI Frameworks for Natural Language Processing: Transformers and Recurrent Neural Networks
&lt;/h2&gt;

&lt;p&gt;As a Lead Programmer Analyst with expertise in PHP, Perl, Python, and Shell, I have been following the advancements in Natural Language Processing (NLP) with great interest. Based on my technical understanding, the choice of AI framework for NLP tasks can significantly impact the performance and efficiency of the system. In this article, we will delve into the comparison of two popular AI frameworks for NLP: Transformers and Recurrent Neural Networks (RNNs).&lt;/p&gt;

&lt;h3&gt;
  
  
  Introduction to Transformers and RNNs
&lt;/h3&gt;

&lt;p&gt;Transformers and RNNs are both types of neural networks used for NLP tasks, but they differ significantly in their architecture and approach. RNNs are a type of neural network designed to handle sequential data, such as text or speech. They process the input sequence one step at a time, using the previous steps to inform the current step. This makes RNNs well-suited for tasks like language modeling, machine translation, and text classification.&lt;/p&gt;

&lt;p&gt;Transformers, on the other hand, are a type of neural network introduced in 2017 that has revolutionized the field of NLP. They are designed to handle long-range dependencies in sequential data, making them particularly well-suited for tasks like machine translation, text summarization, and question answering. Transformers use self-attention mechanisms to process the entire input sequence simultaneously, rather than one step at a time like RNNs.&lt;/p&gt;

&lt;h3&gt;
  
  
  Comparing Transformers and RNNs
&lt;/h3&gt;

&lt;p&gt;So, how do Transformers and RNNs compare in terms of performance and efficiency? According to a recent study on Transformer vs RNN in NLP: A Comparative Analysis, Transformers outperform RNNs in many NLP tasks, particularly those that require handling long-range dependencies. This is because Transformers can process the entire input sequence simultaneously, using self-attention mechanisms to learn relationships between words and phrases.&lt;/p&gt;

&lt;p&gt;In contrast, RNNs process the input sequence one step at a time, using recursion to learn relationships between words and phrases. This can make RNNs slower and more computationally expensive than Transformers, particularly for long documents. As noted in Types of Neural Networks: Complete Guide (2026), Transformers have a 15-40% accuracy advantage over RNNs in long documents.&lt;/p&gt;

&lt;p&gt;Another key advantage of Transformers is their ability to parallelize computation, making them much faster to train than RNNs. As noted in RNN vs Transformer: A Deep Dive from Fundamentals to Applications, LSTM processing is inherently sequential, making GPU utilization poor. In contrast, Transformers can take full advantage of GPU acceleration, making them much faster to train.&lt;/p&gt;

&lt;h3&gt;
  
  
  Real-World Applications
&lt;/h3&gt;

&lt;p&gt;So, how are Transformers and RNNs being used in real-world applications? According to Transformers are Multi-State RNNs | Research - AI at Meta, Transformers are being used in a wide range of NLP applications, including machine translation, text summarization, and question answering. RNNs, on the other hand, are still widely used in many NLP applications, particularly those that require handling sequential data.&lt;/p&gt;

&lt;p&gt;Based on my technical understanding as a Lead Programmer Analyst, I believe that the choice of AI framework for NLP tasks will depend on the specific requirements of the project. While Transformers offer many advantages over RNNs, including faster training times and better performance on long-range dependencies, RNNs are still a good choice for many NLP tasks, particularly those that require handling sequential data.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;In conclusion, the choice of AI framework for NLP tasks is a critical decision that can significantly impact the performance and efficiency of the system. Based on my technical understanding, I believe that Transformers offer many advantages over RNNs, including faster training times and better performance on long-range dependencies. However, RNNs are still a good choice for many NLP tasks, particularly those that require handling sequential data.&lt;/p&gt;

&lt;h3&gt;
  
  
  📚 References &amp;amp; Further Reading
&lt;/h3&gt;

&lt;p&gt;For further reading on this topic, I recommend checking out the following resources:&lt;br&gt;
PyTorch Transformer Tutorial&lt;br&gt;
Hugging Face Transformers&lt;br&gt;
Attention Is All You Need&lt;br&gt;
Transformers Are Not That Scary (Part 1)&lt;/p&gt;

&lt;h3&gt;
  
  
  Your Turn
&lt;/h3&gt;

&lt;p&gt;As we continue to explore the possibilities of NLP, I'd love to hear from you: what do you think is the most exciting application of Transformers and RNNs in NLP, and how do you see these technologies evolving in the future? Share your thoughts and let's continue the conversation!&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://artificial-inteligence.phptutorial.co.in/comparing-ai-frameworks-for-nlp/" rel="noopener noreferrer"&gt;https://artificial-inteligence.phptutorial.co.in&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>naturallanguageproce</category>
      <category>transformers</category>
      <category>recurrentneuralnetwo</category>
    </item>
    <item>
      <title>Why “IEC 60076 Compliant” Is Not Enough in Transformer Specifications</title>
      <dc:creator>qing zhang</dc:creator>
      <pubDate>Wed, 12 Aug 2026 03:23:44 +0000</pubDate>
      <link>https://dev.to/qing_zhang_4df0c9f1b3c9b6/why-iec-60076-compliant-is-not-enough-in-transformer-specifications-1958</link>
      <guid>https://dev.to/qing_zhang_4df0c9f1b3c9b6/why-iec-60076-compliant-is-not-enough-in-transformer-specifications-1958</guid>
      <description>&lt;p&gt;In many industrial electrical projects, transformer specifications often include one short sentence:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;“The transformer shall comply with IEC 60076.”&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;At first, this looks clear. IEC 60076 is one of the most widely used international standard series for power transformers, so referencing it is a reasonable starting point.&lt;/p&gt;

&lt;p&gt;But in real projects, this sentence alone is often not enough.&lt;/p&gt;

&lt;p&gt;The reason is simple: IEC 60076 is not just one requirement. It is a family of standards covering different transformer topics, including general requirements, temperature rise, insulation levels, short-circuit withstand, loading, sound level, and dry-type transformer requirements.&lt;/p&gt;

&lt;p&gt;For engineers reviewing transformer quotations, the important question is not only:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;“Does it comply with IEC 60076?”&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The better question is:&lt;/p&gt;

&lt;p&gt;“Which parts of IEC 60076 apply to this project, and how are they reflected in the quotation, test plan, and final documentation?”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Common gaps in transformer specifications&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here are some details that are easy to miss:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Temperature rise basis&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The quotation should clearly define the cooling method, ambient condition, reference temperature, and guaranteed temperature-rise values.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Insulation level&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The rated insulation level should match the system voltage, overvoltage condition, and project requirements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Short-circuit withstand&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For industrial and utility applications, short-circuit performance should not be treated as a vague assumption.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Routine, type, and special tests&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A project should define which tests are required before shipment, whether FAT witness is needed, and what documents must be provided.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Guaranteed particulars&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Losses, impedance, sound level, temperature rise, and other guaranteed values should be clearly stated and traceable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why this matters&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A transformer is expected to operate for many years. Many problems during procurement or commissioning do not come from the transformer concept itself, but from unclear technical requirements before ordering.&lt;/p&gt;

&lt;p&gt;A well-prepared IEC 60076 review helps engineers compare suppliers more fairly and reduces disagreement during factory acceptance testing.&lt;/p&gt;

&lt;p&gt;I found this practical &lt;a href="https://milestonelectric.com/iec-60076-transformer-guide/" rel="noopener noreferrer"&gt;IEC 60076 transformer guide&lt;/a&gt; useful because it breaks the standard review into buyer-focused checkpoints instead of treating IEC compliance as just a checkbox.&lt;/p&gt;

&lt;p&gt;For transformer projects, “IEC 60076 compliant” should be the beginning of the technical review, not the end of it.&lt;/p&gt;

</description>
      <category>electricalengineering</category>
      <category>powerengineering</category>
      <category>transformers</category>
      <category>engineering</category>
    </item>
    <item>
      <title>From Sparse Attention to MoE: Why K3's 896 Experts Only Activate 1.8% Per Token</title>
      <dc:creator>AICDragon</dc:creator>
      <pubDate>Tue, 11 Aug 2026 03:16:11 +0000</pubDate>
      <link>https://dev.to/cdragon123code/from-sparse-attention-to-moe-why-k3s-896-experts-only-activate-18-per-token-1nl3</link>
      <guid>https://dev.to/cdragon123code/from-sparse-attention-to-moe-why-k3s-896-experts-only-activate-18-per-token-1nl3</guid>
      <description>&lt;h1&gt;
  
  
  From Sparse Attention to MoE: Why K3's 896 Experts Only Activate 1.8% Per Token
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;p&gt;This is the third installment in a series on the evolution of attention mechanisms.&lt;/p&gt;

&lt;p&gt;Part 1 covered the sequence dimension: from GPT-2's full attention to KV Cache, linear attention, and KDA — seven years of progress.&lt;br&gt;
Part 2 covered the inter-layer dimension: from simple residual summation to Attention Residuals and Depth-Attention — selective cross-layer communication at near-zero cost.&lt;/p&gt;

&lt;p&gt;This article explores the third dimension: &lt;strong&gt;orthogonal computation&lt;/strong&gt; — when Transformers face the demand of "make the model bigger without making inference slower," the answer is "most parameters stay idle." This is the story from sparse attention to MoE to Stable LatentMoE. Let's begin with one number: K3 has 896 experts, but at inference time each token only activates 16 — that's 1.8%.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. The Origin of the Problem: The Curse of All-or-Nothing
&lt;/h2&gt;

&lt;p&gt;Standard Transformers operate on an implicit assumption: &lt;strong&gt;every token at every layer must pass through all parameters&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Layer 0: Token -&amp;gt; (Attention + FFN) -&amp;gt; hidden state
Layer 1: Token -&amp;gt; (Attention + FFN) -&amp;gt; ...
...
Layer 92: Token -&amp;gt; (Attention + FFN) -&amp;gt; predict next token
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every layer's FFN processes every token. "Answer a primary-school math problem" and "write operating system kernel code" engage entirely different cognitive circuits — yet the Transformer is forced to use the same parameters for both.&lt;/p&gt;

&lt;p&gt;This creates two fatal consequences:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Parameter count is constrained.&lt;/strong&gt; More parameters means more operations per inference — compute cost scales linearly. Want a smarter model? Adding parameters = adding cost.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Wasted compute.&lt;/strong&gt; The simplest token and the hardest token consume exactly the same FLOPs.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;MoE's solution is brutally effective: &lt;strong&gt;prepare multiple sets of "cognitive circuits" (experts), and have each token call only a small subset.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Sounds like common sense. But turning that common sense into an industrially stable, inference-efficient model took several years.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Three Cards in MoE's Evolution
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Card 1: Switch Transformer (2021, Google) — Moving MoE from Lab to Factory
&lt;/h3&gt;

&lt;p&gt;MoE itself is an old idea (Jacobs et al., 1991), but before the LLM era it was stuck in the lab due to training instability.&lt;/p&gt;

&lt;p&gt;Switch Transformer (Fedus et al., JMLR 2022) did two crucial things:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Solved large-scale training stability.&lt;/strong&gt; Used capacity factor to cap tokens per expert, and auxiliary loss to balance routing load.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Trained a 1.6T-parameter model on C4&lt;/strong&gt;, activating far fewer parameters at inference than the total count.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But Switch used &lt;strong&gt;Top-1 routing&lt;/strong&gt; — each token goes to exactly one expert. The advantage is extreme sparsity (minimal activation rate). The problem is obvious: if that one expert fails (overloaded or dropped), the token produces no output — there's no backup.&lt;/p&gt;

&lt;h3&gt;
  
  
  Card 2: Mixtral 8x7B (2023, Mistral) — Top-2 Becomes the Industry Standard
&lt;/h3&gt;

&lt;p&gt;Mistral's Mixtral 8x7B, released in late 2023, used &lt;strong&gt;Top-2 routing&lt;/strong&gt; — each token activates 2 out of 8 experts.&lt;/p&gt;

&lt;p&gt;This marked a key design philosophy shift. Top-1 is "all eggs in one basket." Top-2 begins to accept "spend a bit more compute for significantly better stability and performance." The 8-expert configuration is also clean enough to run on consumer-grade GPUs.&lt;/p&gt;

&lt;p&gt;Mixtral, at 46.7B total parameters (12.9B active), matched or approached comparable dense models on multiple benchmarks while using substantially less compute. This proved that MoE isn't just for gigantic models — it pays off at medium scale too.&lt;/p&gt;

&lt;h3&gt;
  
  
  Card 3: DeepSeek-MoE (2024, DeepSeek) — Fine-Grained Experts + Shared Experts
&lt;/h3&gt;

&lt;p&gt;DeepSeek-MoE (ACL 2024) introduced two of the most important architectural innovations in MoE history:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Fine-grained expert segmentation:&lt;/strong&gt; Split N experts into mN smaller experts, activating mK per token. This enables more flexible combinations — instead of a few large experts handling broad knowledge domains, many small experts perform precise assembly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Shared experts:&lt;/strong&gt; Isolate K_s "shared experts" from the total expert pool, always activated. These handle foundational knowledge every token needs (grammar structure, common phrasing, basic reasoning frameworks), while routed experts focus on domain-differentiated knowledge.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;This design solves MoE's biggest contradiction: "knowledge redundancy."&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In early MoE, every expert could learn the same basics (e.g., "the" can be followed by a noun) because routing selects experts based on token features, and all experts see these high-frequency patterns. Isn't that just wasting parameters?&lt;/p&gt;

&lt;p&gt;The shared expert idea: "Extract that shared part, let everyone use it, stop routed experts from redundantly learning fundamentals."&lt;/p&gt;

&lt;p&gt;DeepSeek-MoE 16B achieved LLaMA2 7B performance at roughly 40% of the compute. DeepSeek-MoE 145B matched DeepSeek 67B using only 28.5% of the compute. This was the first paper to clearly demonstrate that the "fine-grained + shared expert" dual-track architecture has overwhelming advantages in compute efficiency.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This is also the direct predecessor of K3's MoE architecture.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  3. K3's Stable LatentMoE: Pushing DeepSeek-MoE's Three Paths to the Limit
&lt;/h2&gt;

&lt;p&gt;K3's technical report describes the Stable LatentMoE design in detail. Building on DeepSeek-MoE, it pushes three paths:&lt;/p&gt;

&lt;h3&gt;
  
  
  Path 1: Expert Count Jumps from 64 to 896
&lt;/h3&gt;

&lt;p&gt;DeepSeek-MoE already made experts smaller and more numerous, but K3 pushes this to another order of magnitude.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DeepSeek-MoE 16B:   ~64 routing experts + shared experts
K3:                  896 routing experts + 2 shared experts
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The key isn't "896 is a lot" — it's &lt;strong&gt;what 896 implies about how small each expert is&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Let's compute. K3 has 896 routing experts per layer, hidden dim = 7168, latent dim (the compressed dimension before entering routing experts) = 3584, each expert's intermediate dim = 3072.&lt;/p&gt;

&lt;p&gt;One expert = two weight matrices (3584-&amp;gt;3072 + 3072-&amp;gt;3584) = roughly 22M parameters.&lt;/p&gt;

&lt;p&gt;K3 has 2.78T parameters total. 896 experts x 93 layers = roughly 83,328 experts. At 22M each, the expert portion is... far below 2.78T. Because experts are just FFN replacements — the total parameter count includes embeddings, all layers' attention weights, shared experts, and other larger components.&lt;/p&gt;

&lt;p&gt;But the core logic holds: &lt;strong&gt;when experts become small enough, routing ceases to be semantic assignment ("bring in the Python expert") and becomes feature assembly from a pool of fragments.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This leads to K3's most crucial design philosophy, and the most insightful analysis from the lilting channel —&lt;/p&gt;

&lt;h3&gt;
  
  
  The Router Is Not a "Classifier" — It's a "Compute Allocator"
&lt;/h3&gt;

&lt;p&gt;The standard MoE understanding: "the router classifies each token to a domain expert." This understanding is wrong — at least for K3 with 896 experts.&lt;/p&gt;

&lt;p&gt;K3's router is a single line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;scores&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Sigmoid&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;W_r&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;# W_r: 896 x 7168, x: hidden state
# Take Top-16, weighted combination by normalized scores
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A linear projection -&amp;gt; Sigmoid -&amp;gt; Top-16. No complex operations whatsoever.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But this works not because the router is "smart," but because x itself has already been thoroughly processed by preceding layers' Attention and FFN.&lt;/strong&gt; Just as BERT hidden states are good enough for a simple linear classifier to perform NLU tasks — K3's hidden state, after passing through dozens of layers before reaching the router, is already a highly structured representation space. A single linear projection is sufficient for the final "routing decision."&lt;/p&gt;

&lt;p&gt;From another angle: with 896 experts, expecting a simple linear classifier to correctly assign each token to "exactly the right 16 experts" is clearly over-idealized. &lt;strong&gt;The router's real job isn't "find the best 16" — it's "under load-balancing constraints, give most tokens a reasonable set of 16."&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is why K3 invested massive engineering effort in load balancing —&lt;/p&gt;

&lt;h3&gt;
  
  
  Quantile Balancing: The Load-Balancing Challenge of 896 Experts
&lt;/h3&gt;

&lt;p&gt;MoE routing training has a classic dilemma:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Don't intervene in routing -&amp;gt; tokens flood a few experts -&amp;gt; GPU load imbalance -&amp;gt; some experts starve (insufficient training data)&lt;/li&gt;
&lt;li&gt;Force balance -&amp;gt; same input routed to different experts across training steps -&amp;gt; experts learn highly similar things -&amp;gt; pseudo-balance&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;K3's solution is &lt;strong&gt;Quantile Balancing&lt;/strong&gt;: at each training step, compute quantile thresholds from the router score distribution — experts above this threshold receive a target number of tokens. Then update per-expert selection bias based on deviation from the target.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Crucially: this bias is only used during training. Fixed at inference.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This means K3 has already gained complete experience during training on "how to achieve load balance among 896 choices," and at inference it simply uses a fixed bias to prevent catastrophic load skew.&lt;/p&gt;

&lt;h3&gt;
  
  
  Path 2: Latent Compression + 2 Shared Experts
&lt;/h3&gt;

&lt;p&gt;Another key design in Stable LatentMoE: before entering routing experts, compress the 7168-dimensional hidden state into a 3584-dimensional latent space.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x (7168) -&amp;gt; W_down -&amp;gt; z (3584) -&amp;gt; 16 routing experts -&amp;gt; u (3584) -&amp;gt; W_up -&amp;gt; RMSNorm -&amp;gt; output
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why? Two reasons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Reduces per-expert parameter count and compute (input dimension halved)&lt;/li&gt;
&lt;li&gt;Reduces the information dimension the router needs to handle&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But compression loses information. So K3 retains &lt;strong&gt;2 always-activated shared experts&lt;/strong&gt; — they operate on the full 7168-dimensional hidden space, without latent compression.&lt;/p&gt;

&lt;p&gt;Final output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;y&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;E1_shared&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nc"&gt;E2_shared&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nc"&gt;W_up&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;RMSNorm&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The 2 shared experts handle "foundational features everyone needs." The 16 routed experts handle "differentiated features specific to each token." Clean division of labor.&lt;/p&gt;

&lt;h3&gt;
  
  
  Path 3: 1.8% Activation Rate — It's Not a Bug, It's a Feature
&lt;/h3&gt;

&lt;p&gt;Back to that number: 896 experts, only 16 activated. 1.8%.&lt;/p&gt;

&lt;p&gt;Why not more? Say, 32 (3.6%)?&lt;/p&gt;

&lt;p&gt;K3's technical report doesn't directly provide this ablation, but we can infer from the architecture:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Latent space capacity bottleneck.&lt;/strong&gt; Latent dim = 3584. 16 experts already approach this dimension's information saturation. Adding more experts -&amp;gt; additional FFN capacity can't be effectively transmitted through the latent bottleneck -&amp;gt; diminishing marginal returns.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Cross-GPU communication cost.&lt;/strong&gt; 896 experts are distributed across multiple GPUs. Each additional activated expert means more all-to-all communication across GPUs. K3's official docs explicitly recommend 64+ accelerators for deployment — when you're already doing all-to-all on a cluster that large, each extra expert adds real latency.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;DeepSeek-MoE already validated: fine-grained + fewer activations &amp;gt; coarse-grained + more activations.&lt;/strong&gt; Rather than activating 40 experts each learning a little, let 16 small experts each learn their part well.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;1.8% isn't a design target — it's the optimal convergence point shaped jointly by the latent bottleneck, communication costs, and expert granularity.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  4. The Evolution at a Glance: From Dense to 896-Expert
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csvs"&gt;&lt;code&gt;&lt;span class="k"&gt;Year&lt;/span&gt;    &lt;span class="k"&gt;Model&lt;/span&gt;                  &lt;span class="k"&gt;Routing&lt;/span&gt; &lt;span class="k"&gt;Strategy&lt;/span&gt;    &lt;span class="k"&gt;Experts&lt;/span&gt;&lt;span class="err"&gt;/&lt;/span&gt;&lt;span class="k"&gt;Layer&lt;/span&gt;    &lt;span class="k"&gt;Active&lt;/span&gt;    &lt;span class="k"&gt;Shared&lt;/span&gt; &lt;span class="k"&gt;Experts&lt;/span&gt;

&lt;span class="mf"&gt;2021&lt;/span&gt;    &lt;span class="k"&gt;Switch&lt;/span&gt; &lt;span class="k"&gt;Transformer&lt;/span&gt;     &lt;span class="k"&gt;Top&lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="mf"&gt;1&lt;/span&gt;               &lt;span class="mf"&gt;64&lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="mf"&gt;2048&lt;/span&gt;          &lt;span class="mf"&gt;1&lt;/span&gt;         &lt;span class="k"&gt;None&lt;/span&gt;
&lt;span class="mf"&gt;2023&lt;/span&gt;    &lt;span class="k"&gt;Mixtral&lt;/span&gt; &lt;span class="mf"&gt;8&lt;/span&gt;&lt;span class="k"&gt;x&lt;/span&gt;&lt;span class="mf"&gt;7&lt;/span&gt;&lt;span class="k"&gt;B&lt;/span&gt;           &lt;span class="k"&gt;Top&lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="mf"&gt;2&lt;/span&gt;               &lt;span class="mf"&gt;8&lt;/span&gt;                &lt;span class="mf"&gt;2&lt;/span&gt;         &lt;span class="k"&gt;None&lt;/span&gt;
&lt;span class="mf"&gt;2024&lt;/span&gt;    &lt;span class="k"&gt;DeepSeek&lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="k"&gt;MoE&lt;/span&gt; &lt;span class="mf"&gt;16&lt;/span&gt;&lt;span class="k"&gt;B&lt;/span&gt;       &lt;span class="k"&gt;Fine&lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="k"&gt;grained&lt;/span&gt; &lt;span class="k"&gt;Top&lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="k"&gt;K&lt;/span&gt;  &lt;span class="err"&gt;~&lt;/span&gt;&lt;span class="mf"&gt;64&lt;/span&gt;              &lt;span class="err"&gt;~&lt;/span&gt;&lt;span class="mf"&gt;6&lt;/span&gt;        &lt;span class="k"&gt;K&lt;/span&gt;&lt;span class="err"&gt;_&lt;/span&gt;&lt;span class="k"&gt;s&lt;/span&gt;
&lt;span class="mf"&gt;2024&lt;/span&gt;    &lt;span class="k"&gt;DeepSeek&lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="k"&gt;MoE&lt;/span&gt; &lt;span class="mf"&gt;145&lt;/span&gt;&lt;span class="k"&gt;B&lt;/span&gt;      &lt;span class="k"&gt;Fine&lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="k"&gt;grained&lt;/span&gt; &lt;span class="k"&gt;Top&lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="k"&gt;K&lt;/span&gt;  &lt;span class="err"&gt;~&lt;/span&gt;&lt;span class="mf"&gt;192&lt;/span&gt;             &lt;span class="err"&gt;~&lt;/span&gt;&lt;span class="mf"&gt;18&lt;/span&gt;       &lt;span class="k"&gt;K&lt;/span&gt;&lt;span class="err"&gt;_&lt;/span&gt;&lt;span class="k"&gt;s&lt;/span&gt;
&lt;span class="mf"&gt;2026&lt;/span&gt;    &lt;span class="k"&gt;Kimi&lt;/span&gt; &lt;span class="k"&gt;K&lt;/span&gt;&lt;span class="mf"&gt;3&lt;/span&gt;                &lt;span class="k"&gt;Quantile&lt;/span&gt; &lt;span class="k"&gt;Top&lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="mf"&gt;16&lt;/span&gt;     &lt;span class="mf"&gt;896&lt;/span&gt;              &lt;span class="mf"&gt;16&lt;/span&gt;        &lt;span class="mf"&gt;2&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Clear trends:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Expert count is increasing, but active count stays in a stable range&lt;/strong&gt; (1-16) — not because 16 is a magic number, but because the latent bottleneck and communication costs impose an invisible ceiling&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Shared experts are a watershed&lt;/strong&gt; — nobody did them before DeepSeek; K3 directly inherited the approach&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Load balancing evolved from "aux loss assist" to "quantile direct control"&lt;/strong&gt; — control precision went from "penalize imbalance" to "direct allocation"&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Each expert is getting smaller&lt;/strong&gt; — from a few large experts to hundreds of small ones, routing's meaning shifts from "domain classification" to "feature assembly"&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  5. K3 MoE's Real-World Performance
&lt;/h2&gt;

&lt;p&gt;Data extracted from the official blog and technical report:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Total params: 2.78T&lt;/strong&gt;, active params: 104.2B (roughly 3.7%)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Inference efficiency:&lt;/strong&gt; Despite the routing overhead of 896 experts, K3's team claims 90%+ cache hit rate (in coding scenarios) through the Mooncake decoupled inference architecture, serving million-token contexts at $0.30/M tokens (cache-hit pricing)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Training efficiency:&lt;/strong&gt; Introduced fully balanced expert-parallel training with static shapes and no host-synchronization critical path, making 896-expert scale training feasible&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;More importantly, the synergy between MoE and other innovations: KDA (from Part 1) + Attention Residuals (mentioned in Part 1) + Stable LatentMoE (the protagonist of this article) -&amp;gt; Kimi K3 achieves roughly &lt;strong&gt;2.5x overall scaling efficiency improvement&lt;/strong&gt; over K2.&lt;/p&gt;

&lt;p&gt;This isn't one component's magic — it's three orthogonal optimization dimensions stacked together: cheaper long contexts (KDA), smarter inter-layer communication (AttnRes), and compute concentrated on the most needed parameters (LatentMoE).&lt;/p&gt;

&lt;h2&gt;
  
  
  6. What's Next: MoE on the Road Ahead
&lt;/h2&gt;

&lt;p&gt;K3 already does conditional computation at the FFN layer — each token uses a different FFN expert combination. This is just the first step:&lt;/p&gt;

&lt;p&gt;Current K3 is still a 93-layer fixed-depth Transformer — every token, regardless of difficulty, must traverse all 93 layers. Possible evolutionary directions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Dynamic depth:&lt;/strong&gt; Simple tokens exit early, difficult tokens go deeper (ADEPT, 2026)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;MoE-ified Attention:&lt;/strong&gt; Not all tokens need full attention — SALSA uses a router to decide between attention and recurrent (2026)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Layer-level MoE:&lt;/strong&gt; Different layers may have different expert architectures — input-adjacent layers use shared-type, output-adjacent layers use routing-type&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;From FFN routing to full-module routing:&lt;/strong&gt; Not just choosing experts, but choosing "should this layer use attention, SSM, or skip" — turning the model into a token-level dynamic computation graph&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If MoE's essence is "most parameters stay idle," these directions' essence is "most computation stays idle." The engineering implementations are entirely different, but the philosophy shares the same origin.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. What This Means for You
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Three "Don'ts":&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Don't understand MoE through "domain classification."&lt;/strong&gt; Thinking in terms of "math expert" and "code expert" misses the essence. Experts are FFN fragments — what the router allocates isn't semantic roles but compute resources. This understanding directly determines whether you can design efficient routing strategies.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Don't equate "more experts" with "better."&lt;/strong&gt; K3 uses 896 not because it "needs 896," but because under the constraints of fine granularity + latent compression + load balancing, 896 is the optimal tradeoff for training and inference efficiency. Blindly adding experts -&amp;gt; load balancing collapse -&amp;gt; pseudo-balance -&amp;gt; wasted parameters.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Don't treat MoE as an isolated module.&lt;/strong&gt; K3's 2.5x scaling efficiency improvement comes from the synergy of KDA + AttnRes + LatentMoE. The relationship between MoE and attention mechanisms isn't "this replaces that" — it's "simultaneous optimization across multiple dimensions": horizontal (sequence attention compression), vertical (inter-layer information flow), and orthogonal (selective parameter activation).&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Three Numbers to Remember:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;1.8%&lt;/strong&gt; — K3's FFN activation rate per token. The current sparsity-efficiency ceiling for the strongest open-source model.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;28.5%&lt;/strong&gt; — The compute fraction DeepSeek-MoE 145B needs to match DeepSeek 67B Dense. The compute-efficiency baseline for fine-grained MoE.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;90%&lt;/strong&gt; — K3 API's cache hit rate in coding scenarios. Without this level of cache optimization, a 2.78T model could never achieve $0.30/M token pricing.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/MoonshotAI/Kimi-K3" rel="noopener noreferrer"&gt;Kimi K3: Open Frontier Intelligence&lt;/a&gt; — Kimi Team, July 2026, technical report + open weights&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.kimi.com/blog/kimi-k3" rel="noopener noreferrer"&gt;Kimi K3 Tech Blog&lt;/a&gt; — Moonshot AI official blog&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://lilting.ch/en/articles/kimi-k3-moe-experts-router-dynamic-transformer" rel="noopener noreferrer"&gt;K3's router picks 16 of 896 experts: an allocator, not a classifier&lt;/a&gt; — lilting channel, deep architecture analysis&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://arxiv.org/abs/2401.06066" rel="noopener noreferrer"&gt;DeepSeekMoE: Towards Ultimate Expert Specialization&lt;/a&gt; — Damai Dai et al., ACL 2024&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://arxiv.org/abs/2101.03961" rel="noopener noreferrer"&gt;Switch Transformers: Scaling to Trillion Parameter Models&lt;/a&gt; — Fedus et al., JMLR 2022&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://arxiv.org/abs/2401.04088" rel="noopener noreferrer"&gt;Mixtral of Experts&lt;/a&gt; — Jiang et al., Mistral AI, 2024&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://aclanthology.org/2026.acl-long.665/" rel="noopener noreferrer"&gt;The Illusion of Specialization&lt;/a&gt; — ACL 2026, analysis of actual MoE expert behavior&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;This is Part 3 of the "Evolution of Attention Mechanisms" series and the first installment on the "orthogonal dimension." Together, the three parts form a complete coordinate system: horizontal (sequence attention) -&amp;gt; vertical (inter-layer communication) -&amp;gt; orthogonal (selective parameter activation). Coming next: if MoE decouples "parameter count" from "inference cost," what's the next dimension to be decoupled?&lt;/em&gt;&lt;/p&gt;

</description>
      <category>deeplearning</category>
      <category>transformers</category>
      <category>machinelearning</category>
      <category>ai</category>
    </item>
    <item>
      <title>Depth-Attention: Opening an Attention Channel Between Transformer Layers</title>
      <dc:creator>AICDragon</dc:creator>
      <pubDate>Mon, 10 Aug 2026 12:50:49 +0000</pubDate>
      <link>https://dev.to/cdragon123code/depth-attention-opening-an-attention-channel-between-transformer-layers-4l93</link>
      <guid>https://dev.to/cdragon123code/depth-attention-opening-an-attention-channel-between-transformer-layers-4l93</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;This is the second article in my &lt;em&gt;Attention Mechanism Evolution&lt;/em&gt; series. The first covered the horizontal (sequence-dimension) attention optimizations — from GPT-2's full attention to Kimi K3's KDA hybrid architecture. That was one axis. This article tackles the vertical axis: can deeper layers &lt;em&gt;selectively attend&lt;/em&gt; to shallower layers, instead of just blindly summing via residual connections?&lt;/p&gt;

&lt;p&gt;Depth-Attention, proposed by Shanghai Jiao Tong University's LUMIA Lab (arXiv: 2606.05014, accepted at ICML 2026), answers with an elegant design: zero new parameters, zero additional KV cache, under 0.01% extra FLOPs — and a consistent +2.3 point accuracy boost on downstream tasks.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. The Problem: Transformers Are "Blind" Between Layers
&lt;/h2&gt;

&lt;p&gt;Standard self-attention excels at freely selecting information along the &lt;strong&gt;sequence dimension&lt;/strong&gt; — each token can attend to any position in the sequence.&lt;/p&gt;

&lt;p&gt;But switch to another dimension — &lt;strong&gt;between layers&lt;/strong&gt; — and Transformers become startlingly inefficient:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Layer ℓ-1 output → (residual connection: simple summation) → Layer ℓ input
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each residual block just adds the previous layer's output on top of its own — no weighting, no selectivity, no attention. The deeper layers face a hidden state that's just a compressed dump of all prior layer outputs.&lt;/p&gt;

&lt;p&gt;Think of it like this: you write a report and hand each page to a colleague, but they only see the last page. They can't tell whether "page 3's analysis is your best work — read more of it" or "page 15 isn't that important — just skim it."&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This isn't a new problem.&lt;/strong&gt; Recent work has tried to solve it — DenseFormer (learns fixed inter-layer weights for weighted averaging), Hyper-Connections/mHC (multiple parallel residual streams replacing single residual), and Attention Residuals (using softmax attention to adaptively select shallow-layer outputs per token — this is what Kimi K3 uses).&lt;/p&gt;

&lt;h3&gt;
  
  
  But these approaches share a problem
&lt;/h3&gt;

&lt;p&gt;They all operate on &lt;strong&gt;hidden states&lt;/strong&gt; — the model's full intermediate representations, outside the self-attention module itself. This means they need to retain or access these hidden states &lt;em&gt;in addition to&lt;/em&gt; the KV cache during inference.&lt;/p&gt;

&lt;p&gt;Meanwhile, the trend in large models (GQA, MLA) is to &lt;strong&gt;aggressively compress the KV cache&lt;/strong&gt; — DeepSeek uses MLA to compress from 128×d down to 4×d. Adding extra persistent states &lt;em&gt;outside&lt;/em&gt; the KV cache? That's swimming against the current.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Depth-Attention's insight is exactly this contradiction: can we leverage the Q, K, V already inside the attention module, in the same place, without any external state, to achieve cross-layer selective mixing?&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  2. How Depth-Attention Works: Rotating "Sequence Attention" by 90 Degrees
&lt;/h2&gt;

&lt;p&gt;The answer is remarkably simple.&lt;/p&gt;

&lt;p&gt;Standard self-attention operates on the &lt;strong&gt;sequence dimension&lt;/strong&gt; — "the current token attends to all tokens in the sequence."&lt;/p&gt;

&lt;p&gt;Depth-Attention rotates this operation &lt;strong&gt;90 degrees&lt;/strong&gt; — performing the exact same thing on the &lt;strong&gt;depth dimension&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;For layer ℓ, token t:
q_ℓ^t · k_j^t  (current layer query × each shallower layer's key, at the same token position)
  → softmax → depth attention weights α
  → weighted mixture ṽ (depth-mixed value)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The final step is key — everything in self-attention stays unchanged (no Q modification, no K modification, no mask change), &lt;strong&gt;only the value is replaced with the depth-mixed version&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;O_ℓ&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CausalAttn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Q_ℓ&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;K_ℓ&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="err"&gt;̃&lt;/span&gt;&lt;span class="n"&gt;_ℓ&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;# Ṽ_ℓ replaces the original V_ℓ
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Three elegant properties:
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Zero new parameters.&lt;/strong&gt; Depth-Attention fully reuses the Q and K projection matrices already in standard self-attention — the same Q serves both sequence-direction and depth-direction attention. No new parameter matrices at all.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Zero additional KV cache.&lt;/strong&gt; The depth-mixed Ṽ has exactly the same shape as the original V (T×d). During inference, it &lt;strong&gt;replaces&lt;/strong&gt; rather than &lt;strong&gt;appends&lt;/strong&gt; — Ṽ goes into the original V cache slot. Subsequent tokens reading that slot automatically get the depth-mixed version — so the persistent state at inference is identical to a vanilla decoder's KV cache. Not a single byte extra.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Recursive information propagation — the paper's most ingenious design.&lt;/strong&gt; Let me write out the formula clearly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="err"&gt;̃&lt;/span&gt;&lt;span class="n"&gt;_ℓ&lt;/span&gt;&lt;span class="o"&gt;^&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;α_ℓ&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;ℓ&lt;/span&gt; &lt;span class="err"&gt;·&lt;/span&gt; &lt;span class="n"&gt;v_ℓ&lt;/span&gt;&lt;span class="o"&gt;^&lt;/span&gt;&lt;span class="nf"&gt;t  &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="n"&gt;layer&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;s own value)
       + Σ_{j&amp;lt;ℓ} α_ℓ,j · ṽ_j^t  (previous layers&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt; &lt;span class="n"&gt;already&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;mixed&lt;/span&gt; &lt;span class="n"&gt;values&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice the second term: the mixture uses not the &lt;em&gt;raw&lt;/em&gt; v_j, but the &lt;strong&gt;already depth-mixed ṽ_j&lt;/strong&gt;. This means information propagates &lt;strong&gt;cascadingly&lt;/strong&gt; — ṽ_4 contains all mixed info from ṽ_0 through ṽ_3. When ṽ_16 reads from ṽ_4, it gets not just layer 4's raw value, but depth-mixed information already processed by layer 4.&lt;/p&gt;

&lt;p&gt;If it mixed raw v_j, layer 10 could only directly access layer 2's value — with 8 layers of residual stream attenuation in between, the signal is highly degraded. But mixing ṽ_j means: layer 6 reads layer 4 → layer 4's ṽ already contains layer 0's info → layer 10 reads layer 6 → it also indirectly gains contributions from layer 0 and layer 2.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A recursive structure achieves efficient propagation.&lt;/strong&gt; This allows shallow representations to penetrate through many intermediate layers and continue influencing deep layers.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Counter-Intuitive Ablation: More Layers Isn't Always Better
&lt;/h2&gt;

&lt;p&gt;If every layer attended to &lt;em&gt;all&lt;/em&gt; shallower layers, the compute cost would be O(TL²) — non-trivial in deep networks, especially with pipeline parallelism's cross-device communication overhead.&lt;/p&gt;

&lt;p&gt;Depth-Attention addresses this with &lt;strong&gt;strided sampling&lt;/strong&gt;: each layer only attends a sparse subset — itself + {0, s, 2s, ...} among the shallower layers.&lt;/p&gt;

&lt;p&gt;With s=4, layer 20 attends {20, 16, 12, 8, 4, 0}, skipping the 14 layers in between.&lt;/p&gt;

&lt;p&gt;Complexity drops to O(TL/s); with s large enough, it approaches O(T), completely negligible.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But the most counter-intuitive result is the ablation study:&lt;/strong&gt; the paper tested different strides. The result was &lt;strong&gt;not&lt;/strong&gt; "more is better." &lt;strong&gt;s = L/2 (half the total layers) performed best&lt;/strong&gt; — better than denser s=L/4 and sparser s=L.&lt;/p&gt;

&lt;p&gt;Why? The paper doesn't give a definitive explanation, but I think this phenomenon hints at an important principle: &lt;strong&gt;there may be an optimal "reception interval" for information propagation across depth — too dense creates redundancy (adjacent layers' values are highly correlated), too sparse loses critical information.&lt;/strong&gt; s=L/2 happens to provide enough "diversity windows" without falling into the trap where "layer 20's info is highly redundant with neighboring layers 16 and 14."&lt;/p&gt;

&lt;p&gt;This echoes the same design philosophy we saw in part one with Kimi K3's KDA hybrid architecture: &lt;strong&gt;it's not about stacking more — it's about choosing more wisely where to apply it.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  4. GQA Compatibility: Naturally, Freely More Efficient
&lt;/h2&gt;

&lt;p&gt;Modern large models widely use Grouped-Query Attention (GQA), where g query heads share one set of KV heads.&lt;/p&gt;

&lt;p&gt;Depth-Attention handles GQA extremely naturally: &lt;strong&gt;average the g queries within each group, running depth attention at KV head resolution — not query head resolution.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This brings two additional benefits:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;KV head dimension is already several times smaller than hidden size (typically 4x) — running depth attention in this space further shrinks compute and memory&lt;/li&gt;
&lt;li&gt;No head-dimension expansion or alignment needed — just average g queries, zero hyperparameter changes&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In other words: &lt;strong&gt;Depth-Attention is not only overhead-free in GQA scenarios, it's actually &lt;em&gt;more&lt;/em&gt; efficient than in non-GQA scenarios — because depth attention's operating space is naturally compressed by GQA.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Experimental Results: What's the Actual Gain?
&lt;/h2&gt;

&lt;p&gt;The paper ran experiments on Qwen3-style decoder architectures at 1.5B and 3B scales. All models were trained from scratch on 32B tokens from the Pile, with identical data and hyperparameters — a fair comparison.&lt;/p&gt;

&lt;p&gt;Baselines included: Vanilla Transformer, mHC (manifold hyper-connections), Attention Residuals (Kimi K3's approach), and DenseFormer.&lt;/p&gt;

&lt;h3&gt;
  
  
  Key results
&lt;/h3&gt;

&lt;p&gt;At 1.5B scale, zero-shot:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Vanilla Transformer average downstream accuracy: 51.26&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Depth-Attention: 53.56&lt;/strong&gt; (+2.3 points)&lt;/li&gt;
&lt;li&gt;Attention Residuals and mHC fall between Vanilla and Depth-Attention&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;At 3B scale, the gap widens — Depth-Attention reduces perplexity to 6.66 (Vanilla: 7.10), and average accuracy improves from 53.08 to 55.27 (+2.19 points), comprehensively beating all baselines.&lt;/p&gt;

&lt;p&gt;Under 5-shot settings, the pattern holds — Depth-Attention is best at both scales.&lt;/p&gt;

&lt;p&gt;Notably: Attention Residuals, as the strongest baseline, does significantly beat Vanilla — the paper acknowledges this clearly — but Depth-Attention surpasses it on every metric, and does so &lt;em&gt;without adding any inference state.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Efficiency: theory vs. measurements
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Theoretical FLOPs:&lt;/strong&gt; The paper's Appendix B provides detailed derivations of extra FLOPs for each method. Counting per decoder layer:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Depth-Attention extra compute: ≈ 2Td/s FLOPs (s = stride, d = head dim)&lt;/li&gt;
&lt;li&gt;DenseFormer extra compute: ≈ T·d_model·L (weighted summation across all layers)&lt;/li&gt;
&lt;li&gt;Attention Residuals extra compute: ≈ T·d_model·L (similar magnitude)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Plugging in typical values (T=4096, d_model=2048, L=32, s=16), Depth-Attention's extra FLOPs are &lt;strong&gt;less than 0.01% of self-attention FLOPs.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Training wall-clock:&lt;/strong&gt; On a 3B model, Depth-Attention adds only ~1% per-step training time — significantly less than DenseFormer and Attention Residuals.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Inference throughput:&lt;/strong&gt; At 128K token prefill, Depth-Attention throughput is essentially identical to Vanilla (&amp;lt;0.5% difference). Hidden-state methods, by contrast, need explicit extra state management in long-context scenarios, with noticeably higher memory usage.&lt;/p&gt;

&lt;h3&gt;
  
  
  Scaling experiments
&lt;/h3&gt;

&lt;p&gt;The paper tested four scales from 360M to 3B. Depth-Attention maintains its advantage at all scales, with gains showing no sign of saturation. This suggests larger models may also benefit — though this hasn't been verified at 70B+ scale (a limitation the paper acknowledges).&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Weight Visualization: What Did the Model Learn?
&lt;/h2&gt;

&lt;p&gt;The paper visualizes the trained Depth-Attention weight distributions, with several interesting findings:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Early layers focus their depth attention on deeper information sources, not shallower ones.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Concretely: Layers 1-8 (early layers) have self-attention weights dominating in depth attention (α_ℓ,ℓ close to 1) — they don't look much at shallower layers, because there simply aren't enough shallower layers.&lt;/p&gt;

&lt;p&gt;But layers 9-32 (the second half) start dispersing their depth attention weights: deep layers still retain large self-attention weights (preserving their own features) but radiate uniformly toward middle layers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Shallower isn't necessarily more important.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Intuition might suggest "shallow features are more fundamental, deep layers should attend more to them." But from the weight plots, deep layers (e.g., layer 30) don't assign higher attention weights to very shallow layers (layer 0, 4) than to middle layers (layer 12, 16).&lt;/p&gt;

&lt;p&gt;This hints at an interesting learned strategy: &lt;strong&gt;the model learns to extract information at different granularities from different depth levels, rather than simply treating shallow layers as an "information repository."&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Some attention heads are more cross-layer-dependent than others.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Different heads show different degrees of dependence on depth information. Some heads have self-attention weights close to 1 at almost all layers (barely looking at other layers), while others have dispersed weights across the entire depth dimension (actively leveraging cross-layer information). The model thus gains flexibility — use "self-attention-heavy" heads when local fine-grained processing is needed, and "cross-layer-heavy" heads when contextual fusion is needed.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Looped Transformer Experiment: Parameter Sharing Works Too
&lt;/h2&gt;

&lt;p&gt;This is one of the paper's most profound experiments. A Looped Transformer has only a few physical layers (e.g., 4 layers) that execute in a loop (e.g., 8 cycles = 32 total effective layers), with all cycles sharing the same parameters.&lt;/p&gt;

&lt;p&gt;Depth-Attention's gains persist in this setting — each loop cycle acts as a new "logical layer" that can attend to the values from its own previous cycles.&lt;/p&gt;

&lt;p&gt;This result rules out a possible explanation: "Depth-Attention works because different layers have different parameters, so their value semantics differ, making them worth retrieving." In the parameter-sharing scenario, values from different layers are still selectively passed through depth attention — proving that the mechanism's benefit doesn't depend on "different parameters per layer," but rather that &lt;strong&gt;selective cross-depth information transfer is inherently valuable.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Taking it deeper: this result hints at a potential relationship between Depth-Attention and recurrence/SSMs. If parameter sharing works, what Depth-Attention is doing is somewhat like a &lt;strong&gt;soft state-space model&lt;/strong&gt; — selectively remembering and retrieving depth-history information in the value dimension, rather than propagating through fixed residuals.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Depth-Attention vs. Kimi K3's Attention Residuals: A Design Philosophy Divergence
&lt;/h2&gt;

&lt;p&gt;This is the most fascinating comparison — they solve the same problem but choose different positions.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Attention Residuals&lt;/th&gt;
&lt;th&gt;Depth-Attention&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Operation point&lt;/td&gt;
&lt;td&gt;On residual stream (outside module)&lt;/td&gt;
&lt;td&gt;Inside attention (value position)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Target&lt;/td&gt;
&lt;td&gt;Hidden states&lt;/td&gt;
&lt;td&gt;V cache slots&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Extra inference state&lt;/td&gt;
&lt;td&gt;Required (retain shallow hidden)&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;None&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Extra parameters&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Zero&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Information granularity&lt;/td&gt;
&lt;td&gt;Full hidden state (rich)&lt;/td&gt;
&lt;td&gt;Value state (compressed)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Performance (paper comparison)&lt;/td&gt;
&lt;td&gt;Better than vanilla&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Better (at 1.5B/3B)&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Both share the same conceptual origin — enabling deeper layers to selectively attend to shallower ones. The difference is in the tradeoff:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Attention Residuals operates at the &lt;strong&gt;most information-rich&lt;/strong&gt; position (hidden state), but at a cost&lt;/li&gt;
&lt;li&gt;Depth-Attention operates at the &lt;strong&gt;cheapest&lt;/strong&gt; position (V cache), at zero additional cost&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This divergence doesn't have a final answer yet: who wins at 70B+ scale? Nobody knows. But one thing is clear — &lt;strong&gt;Depth-Attention found a "free lunch" path.&lt;/strong&gt; It proved that you don't need to add anything outside the KV cache to get all the benefits of cross-layer selective information transfer.&lt;/p&gt;

&lt;p&gt;This isn't a free lunch — it's the lunch you were already eating, you just didn't realize you could eat it better.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. What This Means
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Architecture evolution: one horizontal, one vertical&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The first article covered sequence-direction (horizontal) attention evolution from full attention to KDA — that was "how to remember more information with less state."&lt;/p&gt;

&lt;p&gt;This article completes the inter-layer (vertical) direction — "how to let deep layers selectively use shallow representations without paying extra."&lt;/p&gt;

&lt;p&gt;Put together:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      ← Sequence direction (horizontal) →
      Full Attn → KV Cache → Linear Attn → DeltaNet → KDA
      (compute → memory → compression → precision → hybrid recipe)

   ↑
   Inter-layer direction (vertical)
   Residual → DenseFormer → Attention Residuals → Depth-Attention
   (sum → weighted → attention → zero-cost attention)
   ↓
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;For model users:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Next time you see a model claiming "cheap long context," don't just look at parameter count and context window — ask "what's your inter-layer communication scheme? How does information flow in the depth direction?"&lt;/li&gt;
&lt;li&gt;Kimi K3 uses Attention Residuals; the next version might switch to Depth-Attention or a variant — keep an eye on this thread&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;For model trainers:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Depth-Attention's zero-parameter nature means a &lt;strong&gt;lossless drop-in replacement&lt;/strong&gt;: no weight changes, no cache changes, no pipeline changes — just modify a few lines of attention code and reliably gain ~2 points&lt;/li&gt;
&lt;li&gt;The paper's code is open-source on GitHub, with a pre-trained 3B checkpoint on HuggingFace for verification&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;For technical investors:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The design philosophy divergence (hidden state vs. value state path) could influence next-generation model architecture choices&lt;/li&gt;
&lt;li&gt;Inter-layer communication is becoming a core optimization dimension alongside "attention compression"&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  10. Limitations (Frankly)
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Limited validation scale.&lt;/strong&gt; The 1.5B and 3B experiments are convincing (32B tokens trained from scratch, 8 downstream tasks), but whether results replicate at 70B+ scale remains unknown. The paper acknowledges this.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mechanism explanation for optimal stride is missing.&lt;/strong&gt; s=L/2 working best is an empirical finding — why this value, and whether better non-uniform sampling strategies exist, leave significant analysis space.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Interaction with other optimizations under-explored.&lt;/strong&gt; Effects when combined with MoE (e.g., K3's 896 experts), compatibility with MLA, differential behavior in prefill vs. decode phases — all await follow-up work.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Is the "dual attention" structure of depth + sequence optimal?&lt;/strong&gt; This is an architectural question — perhaps a future unified primitive will fuse both directional attentions into one operation. Depth-Attention is an important step, but not necessarily the last.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://arxiv.org/abs/2606.05014" rel="noopener noreferrer"&gt;Depth-Attention: Cross-Layer Value Mixing for Language Models&lt;/a&gt; — Boyi Zeng et al., Shanghai Jiao Tong University LUMIA Lab, ICML 2026&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/LUMIA-Group/Depth-Attention" rel="noopener noreferrer"&gt;Code &amp;amp; Models&lt;/a&gt; — GitHub + HuggingFace (3B checkpoint available)&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://arxiv.org/abs/2603.15031" rel="noopener noreferrer"&gt;Attention Residuals&lt;/a&gt; — Kimi Team, 2026 (cross-layer mechanism used in Kimi K3)&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://arxiv.org/abs/2402.02622" rel="noopener noreferrer"&gt;DenseFormer&lt;/a&gt; — Pagliardini et al., NeurIPS 2024&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://arxiv.org/abs/2404.05026" rel="noopener noreferrer"&gt;Hyper-Connections / mHC&lt;/a&gt; — Zhu et al., 2025&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://arxiv.org/abs/2305.13245" rel="noopener noreferrer"&gt;GQA&lt;/a&gt; — Ainslie et al., EMNLP 2023&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;This is the second article in the "Attention Mechanism Evolution" series. Part one covered the horizontal (sequence-direction) evolution — from GPT-2's full attention to Kimi K3's KDA hybrid architecture, with cross-validation across 5 papers, a complete evolution table, and code-level analysis. Part three preview: from sparse attention to MoE — why K3's 896 experts only activate 1.8%.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>deeplearning</category>
      <category>transformers</category>
      <category>machinelearning</category>
      <category>ai</category>
    </item>
    <item>
      <title>Day 040 — Multi-Head Residual (attention by hand)</title>
      <dc:creator>Hariom Lohar</dc:creator>
      <pubDate>Mon, 10 Aug 2026 05:01:36 +0000</pubDate>
      <link>https://dev.to/hariomlohardev/day-040-multi-head-residual-attention-by-hand-ke5</link>
      <guid>https://dev.to/hariomlohardev/day-040-multi-head-residual-attention-by-hand-ke5</guid>
      <description>&lt;p&gt;Hariom Lohar (hariomlohardev on GitHub) — Lab Notebook No.01 · Day 040 · 10 Aug 2026.&lt;/p&gt;

&lt;p&gt;I rebuilt multi-head attention by hand — no PyTorch, just NumPy. From &lt;code&gt;math → NumPy backprop → CNNs → attention&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Live bench + daily logs: &lt;a href="https://hariomlohardev.github.io" rel="noopener noreferrer"&gt;https://hariomlohardev.github.io&lt;/a&gt;&lt;br&gt;
Full log: &lt;a href="https://hariomlohardev.github.io/blog/p/day-040-multi-head-residual/" rel="noopener noreferrer"&gt;https://hariomlohardev.github.io/blog/p/day-040-multi-head-residual/&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Original log on my portfolio (canonical) → &lt;a href="https://hariomlohardev.github.io/blog/p/day-040-multi-head-residual/" rel="noopener noreferrer"&gt;https://hariomlohardev.github.io/blog/p/day-040-multi-head-residual/&lt;/a&gt; — cross-posted to reach more builders. 548 days: 1 Jul 2026 → 31 Dec 2027.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>machinelearning</category>
      <category>transformers</category>
      <category>beginners</category>
    </item>
    <item>
      <title>The KV Cache Is the Bottleneck: A 2026 Field Guide to Attention Variants</title>
      <dc:creator>ai maya</dc:creator>
      <pubDate>Sun, 09 Aug 2026 07:15:29 +0000</pubDate>
      <link>https://dev.to/ai_maya_063fc568e157562fd/the-kv-cache-is-the-bottleneck-a-2026-field-guide-to-attention-variants-33p2</link>
      <guid>https://dev.to/ai_maya_063fc568e157562fd/the-kv-cache-is-the-bottleneck-a-2026-field-guide-to-attention-variants-33p2</guid>
      <description>&lt;p&gt;If you want to understand why 2026's frontier LLMs look the way they do — why one ships Multi-head Latent Attention, another interleaves linear and full attention, a third leans on sliding windows — stop looking at benchmark scores and look at the KV cache. Almost every architectural decision at the frontier this year is, at heart, a fight with the memory that autoregressive decoding leaves behind.&lt;/p&gt;

&lt;p&gt;This is a practitioner's map of that fight: what the KV cache actually costs, the lineage of techniques built to shrink it, and how to choose among them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why the KV cache dominates
&lt;/h2&gt;

&lt;p&gt;During generation, a decoder-only transformer caches the key and value vectors of every past token so it doesn't recompute them each step. That cache is the price of fast decoding, and it is not small.&lt;/p&gt;

&lt;p&gt;The size is brutally simple:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;KV bytes = 2 (K and V) × layers × kv_heads × head_dim × seq_len × batch × dtype_bytes
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two consequences fall out immediately:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;It grows linearly with context and batch.&lt;/strong&gt; Double the context, double the cache. Serve more concurrent users, multiply again. At long context and healthy batch sizes, the KV cache — not the weights — becomes the dominant consumer of accelerator memory.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Decoding is memory-bandwidth bound, not compute bound.&lt;/strong&gt; Generating one token touches the entire cache. You are not FLOP-limited; you are limited by how fast you can stream that cache off HBM. Shrinking the cache is therefore the most direct lever on both memory footprint &lt;em&gt;and&lt;/em&gt; tokens/sec.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Every technique below is a different answer to "how do we make that formula smaller without breaking the model."&lt;/p&gt;

&lt;h2&gt;
  
  
  The lineage of fixes
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Fewer KV heads: MQA → GQA
&lt;/h3&gt;

&lt;p&gt;The first target is &lt;code&gt;kv_heads&lt;/code&gt;. &lt;strong&gt;Multi-Query Attention (MQA)&lt;/strong&gt; collapses all query heads onto a &lt;em&gt;single&lt;/em&gt; shared KV head — a large cut, but it can cost quality and training stability. &lt;strong&gt;Grouped-Query Attention (GQA)&lt;/strong&gt; is the pragmatic compromise that won: query heads are split into groups, each sharing one KV head. With, say, 8 KV heads for 64 query heads you get most of MQA's savings with far less quality loss. GQA is the default in the majority of open-weight models today for exactly this reason.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Compress the cache: Multi-head Latent Attention (MLA)
&lt;/h3&gt;

&lt;p&gt;Instead of storing fewer heads, &lt;strong&gt;MLA&lt;/strong&gt; stores a &lt;em&gt;low-rank latent&lt;/em&gt;. Keys and values are projected down to a small shared latent vector that is cached; the per-head K and V are reconstructed on the fly during attention. The cached object is dramatically smaller than full K/V, yet the model still attends with many effective heads. MLA is the headline reason some 2026 models sustain very long context at serving-friendly memory — it attacks &lt;code&gt;head_dim × kv_heads&lt;/code&gt; directly rather than just cutting head count.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Kill the growing cache entirely: linear attention &amp;amp; SSMs
&lt;/h3&gt;

&lt;p&gt;Softmax attention is O(n²) in compute and O(n) in cache. &lt;strong&gt;Linear attention&lt;/strong&gt; and &lt;strong&gt;state-space models (SSMs, Mamba-style)&lt;/strong&gt; rewrite the operation as a recurrence with a &lt;em&gt;fixed-size&lt;/em&gt; state. There is no cache that grows with sequence length — memory is O(1) in context. The catch is real: a fixed state is a lossy summary, so pure linear models are weaker at precise long-range recall and associative lookup ("what was the exact token 40k ago"). They are fast and cheap; they forget details.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. The 2026 consensus: hybrid, layer-interleaved attention
&lt;/h3&gt;

&lt;p&gt;The dominant pattern this year is not to pick one. Models &lt;strong&gt;interleave&lt;/strong&gt; a minority of full (softmax) attention layers with a majority of linear/SSM layers. The full layers preserve the sharp recall that pure linear loses; the linear layers carry the long-context load cheaply. The result is near-linear memory scaling with most of the quality of full attention. When you read that a 2026 release is "hybrid attention," this layer-wise interleaving is almost always what is meant.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Bound the window: sliding-window attention + sinks
&lt;/h3&gt;

&lt;p&gt;Orthogonal to the above, &lt;strong&gt;sliding-window attention&lt;/strong&gt; simply caps how far back each token attends (e.g., the last few thousand tokens), making the cache constant-size past the window. Naively this destroys long-context behavior, so it is paired with tricks like &lt;strong&gt;attention sinks&lt;/strong&gt; — keeping the first few tokens always in view — which stabilize very long generations. Cheap, effective for many workloads, and easy to combine with GQA.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two more multipliers worth knowing
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Quantized KV cache.&lt;/strong&gt; The &lt;code&gt;dtype_bytes&lt;/code&gt; term is a free-ish win: storing the cache in FP8 or INT8 instead of FP16 halves or quarters it with modest quality impact. In 2026 this is close to standard for long-context serving.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Paged KV memory.&lt;/strong&gt; PagedAttention (the idea behind vLLM's throughput) doesn't shrink the cache — it stops you from &lt;em&gt;wasting&lt;/em&gt; it. By allocating the cache in fixed pages instead of one contiguous per-request block, it removes fragmentation and lets you pack far more concurrent sequences into the same HBM. Architecture shrinks the cache; paging spends what's left efficiently.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to choose
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Building a general open-weight model?&lt;/strong&gt; GQA is the safe, proven baseline. You will not be criticized for it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Chasing long context at serving-friendly memory?&lt;/strong&gt; MLA-style latent compression is the strongest single lever, at the cost of implementation complexity.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Throughput on shorter contexts, or edge deployment?&lt;/strong&gt; Sliding window + GQA + quantized cache is a cheap, robust stack.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Very long context where some recall loss is acceptable?&lt;/strong&gt; A hybrid linear/full interleave gives you near-linear scaling — validate recall on &lt;em&gt;your&lt;/em&gt; long-context tasks before committing.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Serving any of the above?&lt;/strong&gt; Quantize the cache and use a paged runtime. These compose with every architecture and are the lowest-effort wins on the list.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The real takeaway
&lt;/h2&gt;

&lt;p&gt;The lesson of 2026 is that model architecture and the serving stack are now &lt;strong&gt;co-designed&lt;/strong&gt;. You cannot reason about an attention variant without reasoning about its KV cache, its memory bandwidth, and how a runtime will page it. The models that feel fast and cheap in production didn't get there by accident — they were shaped, layer by layer, by the cost of remembering.&lt;/p&gt;

&lt;p&gt;When you evaluate the next "new architecture," skip the leaderboard for a minute and ask the only question that predicts its serving cost: &lt;em&gt;what happens to the KV cache?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;What's your KV strategy in production — GQA, latent compression, hybrid, or just quantize-and-page? Curious what's holding up under real load.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>machinelearning</category>
      <category>transformers</category>
    </item>
    <item>
      <title>Building Custom AI Models for Sentiment Analysis with Transformers Part 1: Introduction to Transformer Architecture</title>
      <dc:creator>Vijay Vinoth</dc:creator>
      <pubDate>Fri, 07 Aug 2026 11:54:40 +0000</pubDate>
      <link>https://dev.to/vijay_vinoth_8e7abfd3f5b5/building-custom-ai-models-for-sentiment-analysis-with-transformers-part-1-introduction-to-3fa8</link>
      <guid>https://dev.to/vijay_vinoth_8e7abfd3f5b5/building-custom-ai-models-for-sentiment-analysis-with-transformers-part-1-introduction-to-3fa8</guid>
      <description>&lt;h2&gt;
  
  
  Introduction to Building Custom AI Models for Sentiment Analysis with Transformers
&lt;/h2&gt;

&lt;p&gt;The field of artificial intelligence (AI) has witnessed tremendous growth in recent years, with significant advancements in natural language processing (NLP) and machine learning. One of the most influential architectures in NLP is the Transformer model, introduced in the paper "Attention is All You Need" by Vaswani et al. in 2017. Based on my technical understanding as a Lead Programmer Analyst, I can attest that the Transformer architecture has revolutionized the way we approach sequence-to-sequence tasks, including sentiment analysis.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding the Transformer Architecture
&lt;/h2&gt;

&lt;p&gt;The Transformer model is primarily designed for sequence-to-sequence tasks, where the input and output sequences are of varying lengths. This is particularly useful in NLP tasks, such as machine translation, text summarization, and sentiment analysis. The Transformer architecture consists of an encoder and a decoder. The encoder takes in a sequence of tokens (e.g., words or characters) and outputs a sequence of vectors, which are then used by the decoder to generate the output sequence.&lt;/p&gt;

&lt;p&gt;The Transformer encoder consists of a stack of identical layers, each comprising two sub-layers: self-attention and feed-forward neural networks. The self-attention mechanism allows the model to attend to different parts of the input sequence simultaneously and weigh their importance. This is particularly useful in sentiment analysis, where the context of a sentence or phrase can significantly impact the sentiment.&lt;/p&gt;

&lt;p&gt;The Transformer decoder also consists of a stack of identical layers, each comprising three sub-layers: self-attention, encoder-decoder attention, and feed-forward neural networks. The self-attention mechanism in the decoder allows the model to attend to different parts of the output sequence, while the encoder-decoder attention mechanism allows the model to attend to different parts of the input sequence.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Components of the Transformer Architecture
&lt;/h2&gt;

&lt;p&gt;There are several key components of the Transformer architecture that make it particularly well-suited for sentiment analysis:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Self-Attention Mechanism: This mechanism allows the model to attend to different parts of the input sequence simultaneously and weigh their importance. This is particularly useful in sentiment analysis, where the context of a sentence or phrase can significantly impact the sentiment.&lt;/li&gt;
&lt;li&gt;Encoder-Decoder Attention Mechanism: This mechanism allows the model to attend to different parts of the input sequence and use this information to inform the output sequence.&lt;/li&gt;
&lt;li&gt;Feed-Forward Neural Networks: These networks are used in both the encoder and decoder to transform the input and output sequences.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Advantages of the Transformer Architecture
&lt;/h2&gt;

&lt;p&gt;The Transformer architecture has several advantages that make it particularly well-suited for sentiment analysis:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Parallelization: The Transformer architecture can be parallelized more easily than traditional recurrent neural networks (RNNs), making it faster to train and more efficient.&lt;/li&gt;
&lt;li&gt;Scalability: The Transformer architecture can handle longer input sequences than traditional RNNs, making it more suitable for tasks that require analyzing longer pieces of text.&lt;/li&gt;
&lt;li&gt;Flexibility: The Transformer architecture can be used for a variety of NLP tasks, including sentiment analysis, machine translation, and text summarization.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Applications of the Transformer Architecture
&lt;/h2&gt;

&lt;p&gt;The Transformer architecture has been widely adopted in NLP tasks, including:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Sentiment Analysis: The Transformer architecture has been used to achieve state-of-the-art results in sentiment analysis tasks, such as classifying text as positive, negative, or neutral.&lt;/li&gt;
&lt;li&gt;Machine Translation: The Transformer architecture has been used to achieve state-of-the-art results in machine translation tasks, such as translating text from one language to another.&lt;/li&gt;
&lt;li&gt;Text Summarization: The Transformer architecture has been used to achieve state-of-the-art results in text summarization tasks, such as summarizing long pieces of text into shorter summaries.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In conclusion, the Transformer architecture is a powerful tool for NLP tasks, including sentiment analysis. Its ability to attend to different parts of the input sequence simultaneously and weigh their importance makes it particularly well-suited for tasks that require analyzing complex pieces of text. Based on my technical understanding as a Lead Programmer Analyst, I believe that the Transformer architecture has the potential to revolutionize the field of NLP and achieve state-of-the-art results in a variety of tasks.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Your Turn&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;As we continue to explore the possibilities of building custom AI models for sentiment analysis with Transformers, we would like to ask: What are some potential applications of the Transformer architecture in sentiment analysis that you think have not been fully explored yet, and how do you think the architecture could be modified or extended to better suit these applications? Share your thoughts and opinions in the comments below!&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://artificial-inteligence.phptutorial.co.in/building-custom-ai-models-for-sentiment-analysis-with-transformers-part-1-introduction-to-transformer-architecture/" rel="noopener noreferrer"&gt;https://artificial-inteligence.phptutorial.co.in&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>sentimentanalysis</category>
      <category>transformers</category>
      <category>transformerarchitect</category>
    </item>
    <item>
      <title>Inside the Mixture-of-Experts layer: softmax gating, top-k routing, capacity, and the load-balancing loss</title>
      <dc:creator>Devanshu Biswas</dc:creator>
      <pubDate>Fri, 07 Aug 2026 04:20:50 +0000</pubDate>
      <link>https://dev.to/dev48v/inside-the-mixture-of-experts-layer-softmax-gating-top-k-routing-capacity-and-the-2dj5</link>
      <guid>https://dev.to/dev48v/inside-the-mixture-of-experts-layer-softmax-gating-top-k-routing-capacity-and-the-2dj5</guid>
      <description>&lt;p&gt;A dense Transformer runs &lt;strong&gt;every&lt;/strong&gt; token through the &lt;strong&gt;same&lt;/strong&gt; feed-forward block, so capacity (parameters) and cost (FLOPs) are welded together — to get a smarter model you pay more per token. A Mixture-of-Experts layer breaks that weld. It replaces the one shared FFN with &lt;code&gt;N&lt;/code&gt; independent expert MLPs plus a tiny gating network, and keeps only a few experts per token. Params scale with &lt;code&gt;N&lt;/code&gt;; FLOPs per token stay fixed. More knowledge, roughly the same compute. That decoupling is how Switch Transformer and Mixtral-8x7B (≈47B params, only ≈13B active per token) work.&lt;/p&gt;

&lt;h2&gt;
  
  
  The gate — a softmax over the experts
&lt;/h2&gt;

&lt;p&gt;The gate is a single linear layer &lt;code&gt;W_g&lt;/code&gt; that maps a token to one logit per expert; softmax turns those into a distribution — how much this token wants each expert.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;softmax&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;z&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;z&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;max&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;                 &lt;span class="c1"&gt;# stability, doesn't change the result
&lt;/span&gt;    &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;gate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Wg&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;                    &lt;span class="c1"&gt;# Wg: (N_experts, d)
&lt;/span&gt;    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;softmax&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Wg&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;          &lt;span class="c1"&gt;# p[e] = P(expert e | token x)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Top-k routing — the sparsity
&lt;/h2&gt;

&lt;p&gt;Sparsity is the whole point: do not run all &lt;code&gt;N&lt;/code&gt; experts, keep only the &lt;strong&gt;top-k&lt;/strong&gt; gate entries (k=1 in Switch, k=2 in Mixtral). Renormalize just those k weights so they sum to 1 again — they become the mixing coefficients for combining the chosen experts' outputs, &lt;code&gt;y = Σ_{e∈top-k} g̃_e · E_e(x)&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;top_k&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;idx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;argsort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;)[::&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;][:&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;   &lt;span class="c1"&gt;# indices of the k largest gate probs
&lt;/span&gt;    &lt;span class="n"&gt;w&lt;/span&gt;   &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;w&lt;/span&gt;   &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;               &lt;span class="c1"&gt;# renormalize over the kept experts
&lt;/span&gt;    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt;                   &lt;span class="c1"&gt;# experts to run + their weights
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because &lt;code&gt;k&lt;/code&gt; is fixed, the FLOPs per token stay constant no matter how many experts you add. Grow &lt;code&gt;N&lt;/code&gt; and you add parameters, not compute.&lt;/p&gt;

&lt;h2&gt;
  
  
  Capacity — a hardware budget that drops overflow
&lt;/h2&gt;

&lt;p&gt;Real hardware wants dense, equal-sized batches per expert, so each expert gets a fixed number of slots &lt;code&gt;C = f·(T·k / N)&lt;/code&gt;. Dispatch tokens in arrival order; once an expert is full, extra tokens &lt;strong&gt;overflow&lt;/strong&gt; and are dropped — they skip the layer through the residual connection. The capacity factor &lt;code&gt;f&lt;/code&gt; buys slack against imbalance; shrink it toward 0.25 and even balanced routing starts dropping tokens. Capacity is a budget, not a correctness knob.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idxs&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;1.25&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;C&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ceil&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;     &lt;span class="c1"&gt;# slots per expert
&lt;/span&gt;    &lt;span class="n"&gt;load&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;zeros&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="n"&gt;kept&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;token_experts&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;idxs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;          &lt;span class="c1"&gt;# tokens in arrival order
&lt;/span&gt;        &lt;span class="n"&gt;keep&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;token_experts&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;load&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;C&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;load&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;keep&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;# accepted
&lt;/span&gt;            &lt;span class="c1"&gt;# else: OVERFLOW -&amp;gt; dropped, token uses the residual
&lt;/span&gt;        &lt;span class="n"&gt;kept&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;keep&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;kept&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;load&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;C&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The auxiliary load-balancing loss
&lt;/h2&gt;

&lt;p&gt;A raw gate collapses: whichever experts get picked early get trained more, get picked more — rich-get-richer, until a few experts dominate and the rest die. Switch adds an auxiliary loss to the training objective:&lt;/p&gt;

&lt;p&gt;$$L_{aux} = N \cdot \sum_e f_e \cdot P_e$$&lt;/p&gt;

&lt;p&gt;where &lt;code&gt;f_e&lt;/code&gt; is the fraction of tokens dispatched to expert &lt;code&gt;e&lt;/code&gt; (a hard count) and &lt;code&gt;P_e&lt;/code&gt; is the mean soft router probability for &lt;code&gt;e&lt;/code&gt;. It is minimized at &lt;code&gt;1&lt;/code&gt; exactly when usage is uniform, and climbs toward &lt;code&gt;N&lt;/code&gt; under total collapse — so pulling it down &lt;em&gt;is&lt;/em&gt; load balancing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;aux_loss&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;P_soft&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dispatch_counts&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;dispatch_counts&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;T&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;# fraction of routed tokens per expert
&lt;/span&gt;    &lt;span class="n"&gt;P&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;P_soft&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;axis&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;         &lt;span class="c1"&gt;# mean router prob per expert (soft)
&lt;/span&gt;    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;P&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;        &lt;span class="c1"&gt;# = 1 when uniform, ~N when collapsed
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The gradient flows through the &lt;em&gt;soft&lt;/em&gt; &lt;code&gt;P_e&lt;/code&gt; (the hard count &lt;code&gt;f_e&lt;/code&gt; is detached), and through the softmax Jacobian it reduces to a clean rule: push the logit of an over-used expert down. Take a step and the aux loss falls, the load bars level off, and dropped tokens go to zero.&lt;/p&gt;

&lt;p&gt;Put it together — gate every token, take top-k, dispatch under capacity, run the kept experts, gate-weight the outputs, add &lt;code&gt;λ·L_aux&lt;/code&gt; during training — and you have the layer. Total params scale with &lt;code&gt;N&lt;/code&gt;, FLOPs per token scale with &lt;code&gt;k&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Watch a collapsed router genuinely rebalance by gradient descent, live, at &lt;a href="https://dev48v.infy.uk/dl/day56-mixture-of-experts.html" rel="noopener noreferrer"&gt;https://dev48v.infy.uk/dl/day56-mixture-of-experts.html&lt;/a&gt;&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>deeplearning</category>
      <category>transformers</category>
      <category>python</category>
    </item>
    <item>
      <title>RoPE Explained: Encoding Token Position by Rotating Query and Key Vectors</title>
      <dc:creator>Devanshu Biswas</dc:creator>
      <pubDate>Wed, 05 Aug 2026 15:10:21 +0000</pubDate>
      <link>https://dev.to/dev48v/rope-explained-encoding-token-position-by-rotating-query-and-key-vectors-o2o</link>
      <guid>https://dev.to/dev48v/rope-explained-encoding-token-position-by-rotating-query-and-key-vectors-o2o</guid>
      <description>&lt;p&gt;Self-attention is order-blind. The raw &lt;code&gt;QKᵀ&lt;/code&gt; scores are pure content dot-products, so a Transformer has to be &lt;em&gt;told&lt;/em&gt; where each token sits. The 2017 sinusoidal recipe &lt;em&gt;adds&lt;/em&gt; a positional vector to every token; ALiBi &lt;em&gt;adds&lt;/em&gt; a distance bias to the scores. RoPE (Su et al., 2021) does neither — it encodes position by &lt;strong&gt;rotating&lt;/strong&gt; the query and key. It's the scheme behind LLaMA, GPT-NeoX, PaLM, and Mistral, and once you see the trick it's beautifully simple.&lt;/p&gt;

&lt;h2&gt;
  
  
  Rotate the pairs
&lt;/h2&gt;

&lt;p&gt;Split each &lt;code&gt;d&lt;/code&gt;-dimensional query/key vector into &lt;code&gt;d/2&lt;/code&gt; two-dimensional &lt;strong&gt;pairs&lt;/strong&gt;. For a token at position &lt;code&gt;p&lt;/code&gt;, spin pair &lt;code&gt;i&lt;/code&gt; by an angle &lt;code&gt;θ = p · ω_i&lt;/code&gt;. Rotation is a plain 2×2 matrix — and because it's orthogonal, it &lt;em&gt;preserves the norm&lt;/em&gt;, which is why RoPE never rescales Q or K:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;rot2&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;                 &lt;span class="c1"&gt;# rotate the pair (x, y) by angle a
&lt;/span&gt;    &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cos&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sin&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;  &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;   &lt;span class="c1"&gt;# R(a) @ [x, y]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The frequency schedule
&lt;/h2&gt;

&lt;p&gt;Each pair rotates at its own fixed rate — a geometric ladder from fast to slow:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;rope_freqs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;10000.0&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;arange&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                 &lt;span class="c1"&gt;# one frequency per PAIR
&lt;/span&gt;    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mf"&gt;2.0&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;         &lt;span class="c1"&gt;# omega_i, geometric ladder
&lt;/span&gt;
&lt;span class="nf"&gt;rope_freqs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# [1.0, 0.1, 0.01, 0.001]                # fast -&amp;gt; slow
# wavelengths 2*pi/omega : 6.28 .. 6283  # local -&amp;gt; long-range
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;High-frequency pairs (pair 0 spins at 1 radian/step) encode &lt;em&gt;fine, local&lt;/em&gt; position; low-frequency pairs barely move and encode &lt;em&gt;coarse, long-range&lt;/em&gt; position. It's a built-in multi-scale code. &lt;code&gt;base = 10000&lt;/code&gt; is the original LLaMA value.&lt;/p&gt;

&lt;h2&gt;
  
  
  The relative-offset property — the whole point
&lt;/h2&gt;

&lt;p&gt;Here's the magic. A dot product of two rotated vectors depends &lt;em&gt;only&lt;/em&gt; on the &lt;strong&gt;difference&lt;/strong&gt; of their angles, because of the rotation identity &lt;code&gt;R(mθ)ᵀ R(nθ) = R((n−m)θ)&lt;/code&gt;. So the attention score &lt;code&gt;rope(q, m) · rope(k, n)&lt;/code&gt; becomes a function of the &lt;strong&gt;relative offset &lt;code&gt;m − n&lt;/code&gt; alone&lt;/strong&gt; — even though each vector was rotated by its &lt;em&gt;absolute&lt;/em&gt; position:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;score&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;10000.0&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;rope&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="nf"&gt;rope&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;q&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;randn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;randn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;allclose&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;score&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nf"&gt;score&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;   &lt;span class="c1"&gt;# same offset 2
&lt;/span&gt;&lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;allclose&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;score&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;q&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;               &lt;span class="c1"&gt;# offset 0 -&amp;gt; raw q.k
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Positions &lt;code&gt;(5,3)&lt;/code&gt; and &lt;code&gt;(7,5)&lt;/code&gt; score identically — both have offset 2. Laid out over an &lt;code&gt;(m, n)&lt;/code&gt; grid, the score is constant along every diagonal: a Toeplitz matrix.&lt;/p&gt;

&lt;h2&gt;
  
  
  RoPE attention
&lt;/h2&gt;

&lt;p&gt;In the attention layer you rotate every query and key by its position &lt;em&gt;before&lt;/em&gt; the dot products. V is untouched, nothing is added to the inputs, and the resulting score matrix is automatically relative:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;rope_attention&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Q&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;K&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;10000.0&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;d&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;
    &lt;span class="n"&gt;Qr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="nf"&gt;rope&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Q&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)])&lt;/span&gt;   &lt;span class="c1"&gt;# rotate queries
&lt;/span&gt;    &lt;span class="n"&gt;Kr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="nf"&gt;rope&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;K&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)])&lt;/span&gt;   &lt;span class="c1"&gt;# rotate keys
&lt;/span&gt;    &lt;span class="n"&gt;scores&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Qr&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;Kr&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sqrt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                        &lt;span class="c1"&gt;# relative by construction
&lt;/span&gt;    &lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;triu_indices&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;inf&lt;/span&gt;                  &lt;span class="c1"&gt;# causal mask
&lt;/span&gt;    &lt;span class="n"&gt;A&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scores&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;keepdims&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="n"&gt;A&lt;/span&gt; &lt;span class="o"&gt;/=&lt;/span&gt; &lt;span class="n"&gt;A&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;keepdims&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;A&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;A&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Why it stretches to long context
&lt;/h2&gt;

&lt;p&gt;Push a model past its trained length and the fast pairs alias. Two fixes reuse the exact same code: &lt;strong&gt;position interpolation&lt;/strong&gt; squeezes positions (&lt;code&gt;p → p/s&lt;/code&gt;) so old angles cover new lengths; &lt;strong&gt;NTK-aware scaling&lt;/strong&gt; raises the base so slow pairs stretch while fast ones stay sharp. Both only touch the frequency schedule — the rotation is unchanged, and the relative-offset property survives.&lt;/p&gt;

&lt;p&gt;That's the trade-off table in one line: sinusoidal is absolute and added to inputs; ALiBi is relative and added to scores; RoPE is relative and applied by &lt;em&gt;rotating&lt;/em&gt; Q and K, preserving norm and scaling cleanly to long context.&lt;/p&gt;

&lt;p&gt;Slide the query and key positions, watch the 2D sub-planes rotate and the score stay glued to constant diagonals, and read the full six-step build here: &lt;a href="https://dev48v.infy.uk/dl/day55-rope.html" rel="noopener noreferrer"&gt;https://dev48v.infy.uk/dl/day55-rope.html&lt;/a&gt;&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>deeplearning</category>
      <category>transformers</category>
      <category>python</category>
    </item>
    <item>
      <title>ALiBi: give a Transformer position sense with one line, and let it test longer than it trained</title>
      <dc:creator>Devanshu Biswas</dc:creator>
      <pubDate>Tue, 04 Aug 2026 08:49:13 +0000</pubDate>
      <link>https://dev.to/dev48v/alibi-give-a-transformer-position-sense-with-one-line-and-let-it-test-longer-than-it-trained-1g94</link>
      <guid>https://dev.to/dev48v/alibi-give-a-transformer-position-sense-with-one-line-and-let-it-test-longer-than-it-trained-1g94</guid>
      <description>&lt;p&gt;Self-attention is order-blind: shuffle the tokens and the raw QKᵀ scores come out identical, so a Transformer has to be &lt;em&gt;told&lt;/em&gt; where each token sits. The classic fix adds a positional embedding to every token vector — sinusoidal or learned. But those absolute codes are welded to the exact positions seen in training. Feed a model trained at length 1024 a sequence of 3000 and it meets position indices it has never represented, and quality collapses.&lt;/p&gt;

&lt;p&gt;ALiBi (Press, Smith &amp;amp; Lewis, 2021 — &lt;em&gt;"Train Short, Test Long"&lt;/em&gt;) throws positional embeddings out entirely. Instead it adds a fixed, unlearned linear bias straight onto the attention scores, before the softmax.&lt;/p&gt;

&lt;h2&gt;
  
  
  One matrix: −m·(i−j)
&lt;/h2&gt;

&lt;p&gt;The whole of ALiBi lives in the distance matrix &lt;code&gt;(i − j)&lt;/code&gt; — how many steps a key is &lt;em&gt;behind&lt;/em&gt; the query. Multiply by a slope and negate:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;distance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;arange&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)[:,&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;          &lt;span class="c1"&gt;# (N,1) query index
&lt;/span&gt;    &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;arange&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)[&lt;/span&gt;&lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;:]&lt;/span&gt;          &lt;span class="c1"&gt;# (1,N) key index
&lt;/span&gt;    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;                       &lt;span class="c1"&gt;# (N,N)  &amp;gt;=0 in the causal region
&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;alibi_bias&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nf"&gt;distance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;            &lt;span class="c1"&gt;# -m*(i-j) : linear recency penalty
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's 0 on the diagonal and grows more negative to the left — a penalty that grows linearly with how far back a key is. There is nothing to learn.&lt;/p&gt;

&lt;h2&gt;
  
  
  Per-head slopes form a geometric ladder
&lt;/h2&gt;

&lt;p&gt;Each attention head gets its &lt;em&gt;own&lt;/em&gt; fixed slope, so the model attends at many scales at once. For &lt;code&gt;n&lt;/code&gt; heads the slopes are the geometric sequence &lt;code&gt;m_h = 2^(-8h/n)&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;head_slopes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;              &lt;span class="c1"&gt;# = 2^(-8/n)
&lt;/span&gt;    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;array&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)])&lt;/span&gt;

&lt;span class="nf"&gt;head_slopes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# [0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625]
#  steep (local)  -------------------------------&amp;gt;  gentle (far)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Steep slopes give sharp recency — only the last few keys survive. Gentle slopes let a head gaze far back. Together they're a built-in, multi-scale recency prior.&lt;/p&gt;

&lt;h2&gt;
  
  
  The whole attention change is one added line
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;alibi_attention&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Q&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;K&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;d&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;
    &lt;span class="n"&gt;scores&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Q&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;K&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sqrt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;    &lt;span class="c1"&gt;# (N,N) raw QK^T
&lt;/span&gt;    &lt;span class="n"&gt;scores&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;scores&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nf"&gt;alibi_bias&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# &amp;lt;-- the ONE new line
&lt;/span&gt;    &lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;~&lt;/span&gt;&lt;span class="nf"&gt;causal_mask&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;inf&lt;/span&gt;  &lt;span class="c1"&gt;# can't see the future
&lt;/span&gt;    &lt;span class="n"&gt;A&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="nf"&gt;softmax&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;A&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;A&lt;/span&gt;                    &lt;span class="c1"&gt;# output, attention weights
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;No positional embedding is added to Q, K, or the inputs anywhere. The softmax then turns that straight-line penalty into a clean exponential distance decay, giving each head a bounded effective window of about &lt;code&gt;1/m&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why it extrapolates: distance, not position
&lt;/h2&gt;

&lt;p&gt;The bias reads only &lt;code&gt;i − j&lt;/code&gt;. Slide the whole window along the sequence and every entry is unchanged — it is translation-invariant, so the length &lt;code&gt;N&lt;/code&gt; never appears as an absolute index the way a positional embedding would.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# translation invariance: bias(i,j) depends ONLY on (i-j)
&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;alibi_bias&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.25&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;allclose&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;     &lt;span class="c1"&gt;# same distance 4 -&amp;gt; same bias
&lt;/span&gt;&lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;allclose&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;        &lt;span class="c1"&gt;# distance 0 -&amp;gt; no penalty
&lt;/span&gt;
&lt;span class="c1"&gt;# softmax turns the LINEAR bias into an EXPONENTIAL decay in distance:
#   weight(d)  ∝  exp(-m * d)          # bounded effective window ~ 1/m
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Train at 1024, run at 3000: the model only ever sees relative distances, and far ones are simply taxed more. The attention-by-distance profile is the same shape at any length, which is exactly why a short-trained model extrapolates — and why ALiBi rides in BLOOM and MPT.&lt;/p&gt;

&lt;h2&gt;
  
  
  ALiBi vs sinusoidal vs RoPE
&lt;/h2&gt;

&lt;p&gt;Sinusoidal embeddings are absolute and added to the inputs; they don't extrapolate past trained positions. RoPE is relative but applies its signal by &lt;em&gt;rotating&lt;/em&gt; Q and K. ALiBi needs no embedding table and no rotation — just one added matrix of &lt;code&gt;−m·(i−j)&lt;/code&gt;, with a fixed per-head slope. It's the cheapest recipe of the three, and the one that most naturally handles test sequences longer than training.&lt;/p&gt;

&lt;p&gt;Build the QKᵀ matrix, watch the bias ramp add on top, drag the per-head slope, and slide test length past train length to see the decay curves stay glued together, live at: &lt;a href="https://dev48v.infy.uk/dl/day54-alibi.html" rel="noopener noreferrer"&gt;https://dev48v.infy.uk/dl/day54-alibi.html&lt;/a&gt;&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>deeplearning</category>
      <category>transformers</category>
      <category>python</category>
    </item>
    <item>
      <title>Gated Linear Units explained: the multiplicative valve behind LLaMA and PaLM's SwiGLU FFN</title>
      <dc:creator>Devanshu Biswas</dc:creator>
      <pubDate>Mon, 03 Aug 2026 16:12:14 +0000</pubDate>
      <link>https://dev.to/dev48v/gated-linear-units-explained-the-multiplicative-valve-behind-llama-and-palms-swiglu-ffn-34bl</link>
      <guid>https://dev.to/dev48v/gated-linear-units-explained-the-multiplicative-valve-behind-llama-and-palms-swiglu-ffn-34bl</guid>
      <description>&lt;p&gt;A standard Transformer feed-forward block is dead simple: &lt;code&gt;Linear -&amp;gt; one fixed nonlinearity -&amp;gt; Linear&lt;/code&gt;, where that middle activation (ReLU, GELU) applies the &lt;em&gt;same&lt;/em&gt; elementwise curve to every hidden unit. A Gated Linear Unit throws that single activation out and replaces it with a multiplicative valve. Understanding it is the difference between reading a modern LLM's FFN and being baffled by it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Project the input twice, then multiply
&lt;/h2&gt;

&lt;p&gt;Instead of one weight matrix, a GLU uses two. &lt;code&gt;W&lt;/code&gt; makes a &lt;strong&gt;value&lt;/strong&gt; branch (kept linear); &lt;code&gt;V&lt;/code&gt; makes a &lt;strong&gt;gate&lt;/strong&gt; branch (squashed into &lt;code&gt;(0,1)&lt;/code&gt;). Multiply them element by element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;out = (xW + b) ⊙ σ(xV + c)
        value          gate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The gate decides, per unit and per input, how much of the value is allowed through. A gate near &lt;code&gt;0&lt;/code&gt; shuts that feature off; near &lt;code&gt;1&lt;/code&gt; it passes. In code the forward pass is three lines:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;branches&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;value&lt;/span&gt;    &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;W&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;           &lt;span class="c1"&gt;# linear, NO activation
&lt;/span&gt;    &lt;span class="n"&gt;gate_pre&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;V&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;           &lt;span class="c1"&gt;# will be squashed
&lt;/span&gt;    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;gate_pre&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;glu&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;gate_pre&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;branches&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;gate&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;sigmoid&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;gate_pre&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;       &lt;span class="c1"&gt;# gate in (0, 1)
&lt;/span&gt;    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;gate&lt;/span&gt;            &lt;span class="c1"&gt;# elementwise (Hadamard) product
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Why multiplication buys capacity
&lt;/h2&gt;

&lt;p&gt;A single &lt;code&gt;Linear + ReLU&lt;/code&gt; can only bend each unit with a fixed curve — an &lt;em&gt;additive&lt;/em&gt; nonlinearity. It can't cheaply make unit A's output depend on unit B. A product can: &lt;code&gt;value ⊙ gate&lt;/code&gt; is an AND-like interaction — "let this feature through &lt;strong&gt;only&lt;/strong&gt; when the input also opens the gate." That data-dependent, multiplicative routing is a strictly richer primitive, which is why a gated FFN reaches a lower loss at the same FLOP budget.&lt;/p&gt;

&lt;h2&gt;
  
  
  The family is just which squasher you put on the gate
&lt;/h2&gt;

&lt;p&gt;GLU -&amp;gt; GEGLU -&amp;gt; SwiGLU differ in exactly one thing: the gate activation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;sigmoid&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mf"&gt;1.0&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;1.0&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;gelu&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;                       &lt;span class="c1"&gt;# tanh approximation
&lt;/span&gt;    &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sqrt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;2.0&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pi&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mf"&gt;0.5&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;z&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;1.0&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;tanh&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mf"&gt;0.044715&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)))&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;silu&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;                       &lt;span class="c1"&gt;# SiLU == Swish with beta = 1
&lt;/span&gt;    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;z&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nf"&gt;sigmoid&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;GATE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;GLU&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;sigmoid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;GEGLU&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;gelu&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;SwiGLU&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;silu&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sigmoid saturates in &lt;code&gt;(0,1)&lt;/code&gt; — a pure open/shut valve. GELU and SiLU are smooth and &lt;em&gt;non-monotonic&lt;/em&gt;: they dip slightly below zero near &lt;code&gt;z ≈ -1&lt;/code&gt;, then climb toward the identity, and crucially they are &lt;strong&gt;not capped at 1&lt;/strong&gt;. So a GELU/SiLU gate can also &lt;em&gt;amplify&lt;/em&gt; magnitude, not just attenuate — and it keeps a live gradient where the sigmoid's has vanished. Noam Shazeer's 2020 note &lt;em&gt;"GLU Variants Improve Transformer"&lt;/em&gt; swept these and found GEGLU/SwiGLU give the best quality per parameter.&lt;/p&gt;

&lt;h2&gt;
  
  
  The full SwiGLU FFN — and the ⅔-width rule
&lt;/h2&gt;

&lt;p&gt;In a Transformer the gated hidden goes through a third matrix back to the model width. A plain ReLU FFN has &lt;strong&gt;2&lt;/strong&gt; matrices; a gated FFN has &lt;strong&gt;3&lt;/strong&gt; (&lt;code&gt;W&lt;/code&gt;, &lt;code&gt;V&lt;/code&gt;, &lt;code&gt;W2&lt;/code&gt;), so at the same hidden width it uses ~1.5x the parameters. To keep it parameter-neutral, shrink the hidden width by &lt;code&gt;2/3&lt;/code&gt; — that's LLaMA's &lt;code&gt;d_ff = 8/3 · d_model&lt;/code&gt; instead of &lt;code&gt;4 · d_model&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SwiGLU_FFN&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Module&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;d_model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mult&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="nf"&gt;super&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="n"&gt;d_ff&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;mult&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;d_model&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;          &lt;span class="c1"&gt;# 3 matrices =&amp;gt; shrink 2/3
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;  &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;nn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Linear&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d_model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;d_ff&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;bias&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;False&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;# value  W
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;  &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;nn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Linear&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d_model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;d_ff&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;bias&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;False&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;# gate   V
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;w2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;nn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Linear&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d_ff&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;d_model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;bias&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;False&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;# down   W2
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;forward&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;gated&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;F&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;silu&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;v&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;w&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;     &lt;span class="c1"&gt;# SwiGLU core
&lt;/span&gt;        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;w2&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;gated&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                     &lt;span class="c1"&gt;# back to d_model
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is exactly why &lt;strong&gt;PaLM, LLaMA / 2 / 3 and Mistral&lt;/strong&gt; all use a SwiGLU FFN. Gating itself traces back to Dauphin et al. 2016 (a gated &lt;em&gt;convolutional&lt;/em&gt; LM — the original GLU); Shazeer brought it into the Transformer FFN. If a recent model's feed-forward "looks weird," it's almost always a gated one.&lt;/p&gt;

&lt;p&gt;The mental model that sticks: &lt;strong&gt;value = what, gate = how much&lt;/strong&gt;. Swap the gate activation (σ -&amp;gt; GELU -&amp;gt; SiLU) and you walk the GLU -&amp;gt; GEGLU -&amp;gt; SwiGLU family; pick SiLU and trim the hidden width by ⅔ and you have the LLaMA FFN.&lt;/p&gt;

&lt;p&gt;Feed a live input vector through both branches, flip between the three gates, and probe the valve surface &lt;code&gt;out = value · act(gate)&lt;/code&gt; here: &lt;a href="https://dev48v.infy.uk/dl/day53-gated-linear-units.html" rel="noopener noreferrer"&gt;https://dev48v.infy.uk/dl/day53-gated-linear-units.html&lt;/a&gt;&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>deeplearning</category>
      <category>transformers</category>
      <category>python</category>
    </item>
  </channel>
</rss>
