<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Stanislav Fedotov on Medium]]></title>
        <description><![CDATA[Stories by Stanislav Fedotov on Medium]]></description>
        <link>https://medium.com/@st-fedotov?source=rss-962f037330c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FzaR_dfP9IQIE0CsceBxxw.jpeg</url>
            <title>Stories by Stanislav Fedotov on Medium</title>
            <link>https://medium.com/@st-fedotov?source=rss-962f037330c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:00:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@st-fedotov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Eliminating hallucinations in LLM training: are we there yet?]]></title>
            <link>https://medium.com/nebius/eliminating-hallucinations-in-llm-training-are-we-there-yet-b179d60af101?source=rss-962f037330c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b179d60af101</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[hallucinations]]></category>
            <dc:creator><![CDATA[Stanislav Fedotov]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 15:37:01 GMT</pubDate>
            <atom:updated>2024-12-17T15:37:01.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfzEU_nwHcFmpkl9Gm4Ddw.jpeg" /></figure><p>LLM hallucinations are model outputs that appear ungrounded, inconsistent or nonsensical — a real bane for any AI developer. It’s quite hard to create an AI-powered teaching assistant if an LLM might fabricate a non-existent historical fact. Likewise, today’s LLMs struggle to maintain consistency over long-form narratives, often “forgetting” earlier details after, say, page 100 and inventing new ones.</p><p>Though eliminating hallucinations completely seems far-fetched, recent research on anti-hallucinatory techniques shows promise. In this article, I’ll distill some key insights.</p><p>First, let’s distinguish between two types of hallucinations:</p><ol><li><strong>In-context hallucination</strong>: The model’s outputs are inconsistent with the context provided. A model may forget details and fabricate them anew. <br>For example:<br>User: <em>Help me plan the upcoming AI hackathon. I expect </em><strong><em>100</em></strong><em> guests.</em><br><em>&lt;several rounds of chat&gt;<br></em>LLM: <em>Since we have </em><strong><em>250</em></strong><em> guests…</em></li><li><strong>Extrinsic hallucinations</strong>. The model’s outputs are inconsistent with general knowledge. A classical example is when an LLM fabricates links to scientific papers that don’t exist when discussing recent research.</li></ol><p>Lilian Weng has a <a href="https://lilianweng.github.io/posts/2024-07-07-hallucination/">great blog post</a> on extrinsic hallucinations, covering evaluation and mitigation techniques.</p><p>Hallucinations — the extrinsic kind in particular — are unavoidable. We can’t realistically expect an LLM to be a 100% reliable source of knowledge on everything from the reigns of French kings to Worcestershire sauce ingredients.</p><p>Luckily, random-fact accuracy isn’t typically required in most LLM applications. Instead, an LLM needs to be proficient within a limited area of knowledge, such as details about a company’s products or the number of code repositories in a project. When the knowledge domain is narrow, fending off hallucinations becomes easier and cheaper. Retrieval Augmented Generation (RAG) is invaluable here; by supplying relevant context, RAG can largely eliminate extrinsic hallucinations, letting us focus on reducing in-context hallucinations. This long read will cover exactly that.</p><p>The piece is structured into two parts:</p><ol><li><strong>Mitigating hallucinations with external tools</strong>: Techniques applicable when the LLM is accessible only via API.</li><li><strong>Identifying hallucinatory patterns in LLM activations</strong>: Techniques useful if we can access the LLM’s internals.</li></ol><h3>1. Mitigating hallucinations with external tools</h3><p>If you need the LLM to be accurate about specific facts, it’s best to incorporate them into the context directly. RAG is the primary tool here, gathering all important knowledge in a retrievable database. RAG can also leverage web search instead of a database search, though this tends to be less reliable.</p><p>However, even with RAG, an LLM can still hallucinate. Fortunately, there are ways to mitigate the hallucinations further. The main idea is grounding the LLM’s claims. This can be done, for instance, by:</p><ul><li>Making the LLM cite its sources and possibly checking that these sources truly align with the answer.</li><li>Using an external tool (another LLM call) to extract individual claims from the LLM’s answer and checking them against the context. If misalignment is detected, another LLM call may be used to revise the answer.</li><li>Estimating the answer’s uncertainty.</li></ul><p>Let’s briefly discuss each of these approaches.</p><h3>Forcing citation</h3><p>An example of the first approach is <a href="https://arxiv.org/pdf/2407.19813v1">Improving Retrieval Augmented Language Model with Self-Reasoning</a>. It uses a three-stage process to make RAG outputs more trustworthy:</p><ol><li>Retrieve a list of documents and, for each, ask the LLM to explain its relevance. Irrelevant documents are discarded. If no document is relevant, the LLM bases its answer on general knowledge.</li><li>For relevant documents, instruct the LLM to select key snippets. Then, request that the LLM explain why these snippets can answer the question.</li><li>Compile all relevant snippets and prompt the LLM to provide an analysis (i.e., the “solution” to the original question) and a short answer.</li></ol><p>Here’s an illustration of this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QR3bTY_LZlNj_Qob.png" /></figure><p>An illustration of the SELF-REASONING framework for improving the RALMs. The upper are the basic LLMs, which answer the question by inherent knowledge. The middle is the standard retrieval-augmented LMs, which use retrieved documents to help answer the question. The bottom is our SELF-REASONING framework, which uses self-generated reason trajectories to output answers.</p><h3>Questioning the answer</h3><p>An example of the second approach is <a href="https://arxiv.org/pdf/2210.08726">RARR: Researching and Revising What Language Models Say, Using Language Models</a>. It works through the following stages:</p><ol><li>RAG does its job and produces a long <strong>answer</strong>.</li><li>Several questions (<strong>queries</strong>) are generated about the claims in this answer.</li><li>A <strong>retriever</strong> fetches documents relevant to each question.</li><li>An <strong>agreement model</strong> checks whether the <strong>answer</strong> aligns with the retrieved documents for each question.</li><li>For each disagreement, an LLM is asked to edit the <strong>answer</strong> to mitigate this disagreement.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lT10kI9JsbQJEwl7.png" /></figure><h3>Uncertainty-based hallucination capturing</h3><p>An LLM generates the next token by sampling it from a predicted distribution. And this distribution may be an important source of insights.</p><p>For example, if the query is “<em>Llama-3.2–8B is an</em>”, the word “<em>LLM</em>” should be a highly probable next token, with a probability close to <em>1</em>, while other tokens have probabilities near <em>0</em>. One may say that there is very <strong>low uncertainty</strong>about the continuation.</p><p>On the other hand, the phrase “<em>Time is an</em>” has many potential continuations, resulting in similar, quite low probabilities for multiple tokens. This indicates <strong>high uncertainty</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y-cqvt4PSfJSZwA3.png" /></figure><p>When it comes to facts, there is usually only one correct answer, so we expect uncertainty to be quite low. On the contrary, high uncertainty may suggest that the LLM is confused and possibly hallucinating.</p><p>To measure uncertainty for a particular <em>j</em>-th token, it’s helpful to use the entropy of the predicted probability distribution. <a href="https://en.wikipedia.org/wiki/Entropy">Entropy</a> measures the uncertainty of a distribution: it’s maximal when the distribution is uniform (total uncertainty, where all tokens are equally probable) and minimal when there is exactly one token with probability <em>1</em> while others have <em>0</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s6Ynb_fzV8DnDXLA.png" /></figure><p>The formula of entropy in our case is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X4g19C1h4THC_-3y.png" /></figure><blockquote><em>$H_j=-\sum_{\text{$w$ in the vocabulary}}p_{jw}\log{p_{jw}},$</em></blockquote><p>where <em>p_{jw} </em>is the probability of token <em>w</em> being generated as the <em>j</em>-th token in the answer. For the entire answer, we can either average or take the maximum <em>Hⱼ</em> across <em>j</em>. If this aggregated entropy is too high, we might suspect a hallucination.</p><p>However, not all LLMs output probabilities, and some APIs don’t allow access to this data. In such cases, surrogate methods may be used to assess uncertainty. Let’s look at several examples, taken from <a href="https://www.notion.so/Practical-Generative-AI-Nebius-Academy-adcb980d0e9f405e868c35f58b8de878?pvs=21">SelfCheckGPT: Zero-Resource Black-Box Hallucination Detection for Generative Large Language Models</a>. Along with the candidate answer, generate several more answers with non-zero temperature. Then, do one of the following:</p><ul><li>Calculate the similarity (e.g., using <a href="https://arxiv.org/pdf/1904.09675">BERTScore</a>) between the additional answers and the candidate. If they are all sufficiently similar, this would suggest the answer is likely well-grounded.</li><li>Generate questions based on the candidate answer and check (e.g., using an LLM) if these questions are supported by the other answers (see image below).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rTzYNHsy-rkrfPeB.png" /></figure><h3>Takeaways</h3><p>There are many more approaches, with new ones emerging every month. The main takeaways are:</p><ul><li>Citation forcing, cross-comparison with relevant documents, and clever editing, greased with lots of reasoning, can make things better.</li><li>This requires lots of LLM calls and can easily increase inference cost tenfold. There must be a trade-off between the desire to avoid hallucinations and the need to maintain your application’s economic feasibility.</li></ul><h3>2. Discovering in-context hallucinations deep inside</h3><p>In this section, we’ll take a brief look under the hood of LLMs and review some research on the internal factors that cause in-context hallucinations. As a by-product, these studies often suggest ways to detect hallucinatory behaviour.</p><p><strong>Beware!</strong> This is advanced material, and you may consider revisiting it after studying transformer architecture in more detail in the “LLM Internals” module.</p><h3>Retrieval heads</h3><p>At the core of most LLMs is the attention mechanism, which allows a current token to “look” at previous ones. In today’s LLMs, there are several parallel mechanisms known as “attention heads.” During training, some of these heads develop specific roles that researchers can identify.</p><p>At the same time, it’s often argued that the in-context learning capabilities of LLMs stem from their ability to copy information from the context. The authors of <a href="https://arxiv.org/pdf/2404.15574v1">Retrieval Head Mechanistically Explains Long-Context Factuality</a>studied several LLMs (Llama-2–7B, Mistral-7B-v0.2, Yi-6B, and Qwen1.5–14B) and observed that certain <strong>retrieval heads</strong> are instrumental for fetching information from a long context:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VUpQ4oQflxatyr9J.png" /></figure><p>For a particular query, these heads assign high attention scores to the answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gSINKUGPKCukPX8r.png" /></figure><p>An attention head that performs a copy-paste operation if the token that the head attend to is the same the token being generated. The retrieval score of a head is defined as the frequency of this head’s copy-paste behavior when answering quesions that asks for raw information from the input.</p><p>The authors also observed that retrieval heads display different behaviors:</p><ul><li>Successful retrieval: All or most of the heads point toward the same tokens in the context.</li><li>Incomplete retrieval (missing part of the information): The retrieval heads appear confused, pointing to various tokens.</li><li>Hallucination: The retrieval heads “look” at the beginning of the input.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AB4jnq1CgaLa4EF7.png" /></figure><p>When the model fails to retrieve the full needle, there are two typical errors: (1) incomplete retrieval, where the retrieval heads miss part of the information “eat a sandwich”; (2) hallucination, where the retrieval heads attend to the initial tokens.</p><h3>Lookback lens</h3><p>Another perspective on hallucination occurrence is presented in <a href="https://arxiv.org/pdf/2407.07071">Lookback Lens: Detecting and Mitigating Contextual Hallucinations in Large Language Models Using Only Attention Maps</a>.</p><p>The authors examine the attention pattern as a whole (not just retrieval heads) and argue that in hallucinatory scenarios, attention “looks” at previously generated tokens instead of the context. To measure this, they calculate a “lookback score” across all heads and layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2y1-IWQJOde2eYnG.png" /></figure><blockquote><em>$=\frac{\color{red}{context}}{{\color{red}{context}}+{\color{blue}{new}}}$</em></blockquote><p>where:</p><ul><li><em>Context</em> is the average attention score towards the original context,</li><li><em>New</em> is the average attention score towards previously generated tokens.</li></ul><p>(see picture)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L5vJlMs5GlPPsIpw.png" /></figure><p>An illustration of the Lookback Lens. We extract attention weights and calculate the lookback ratios for all layers and all heads. We train a linear classifier on the concatenated features to predict truthfulness of the generation.</p><p>The authors then build a dataset containing lookback scores across all layers and attention heads for specific generated tokens, labeled hallucinatory or not. They train a linear model on this data, enabling it to predict whether a newly generated token is a hallucination.</p><p>This approach can also be used to create a reduced-hallucination decoding (generation) pipeline. The idea is quite simple: generate several candidate chunks of tokens (remember: we need several pre-generated tokens to assess the lookback score), then choose the one with the highest lookback score, and then continue the process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n1Qe_lxB06s0tzbE.png" /></figure><p>Lookback Lens Guided Decoding: sample multiple chunk candidates, compute lookback ratios from attention maps to be scored by Lookback Lens, and select the best candidate that is less likely to be hallucinations.</p><p>Here is a specific example of iterative decoding with a lookback lens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9_L9ASx3ODZtYVvA.png" /></figure><p>Qualitative example on XSum using the LLaMA-2–7B-Chat model with greedy decoding and Lookback Lens Guided Decoding. The numbers in the parenthesis show the predicted scores from the Lookback Lens.</p><h3>Probing for hallucinations</h3><p>A well-known technique for understanding what’s happening inside an LLM (or any neural network) is <strong>probing</strong>. It involves training simple classifiers on internal representations.</p><p>For example, we might take the internal representations after the 7th transformer layer and train a model on these vectors to predict whether the next token will be hallucinatory.</p><p>Illustration (probe shown in red):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5wlouvROG4B9kqGt.png" /></figure><p>The challenge, however, is deciding which tokens and layers to probe. In the image above, we probed the last token and the first layer. It turns out that this is not necessarily the best option.</p><p>For Q&amp;A tasks, the authors recommend probing on the <strong>exact answer</strong> tokens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Tw50c55LCiGbJI-.png" /></figure><p><a href="https://arxiv.org/pdf/2410.02707">LLMs Know More Than They Show: On the Intrinsic Representation of LLM Hallucinations</a></p><p>Of course, they have to set up a dedicated exact answer extraction procedure (and, rather unsurprisingly, they do it with Mistral-7b-Instruct in few-shot mode). It turns out that representations corresponding to the exact answer tokens contain relevant information for hallucination detection, leading to better performance than when probing the last generated or end-of-question tokens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*WSRxM-uKlklHhF5v.png" /></figure><p>The table above shows hallucination detection AUC scores, which are quite good. Here is the behaviour of AUC across different layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iDC2j5MQEftamjxi.png" /></figure><p>AUC values of a probe error detector across layers and tokens, Mistral-7b-instruct. Generation proceeds from left to right, with detection performance peaking at the exact answer tokens.</p><p>Moreover, the authors observed different types of hallucinatory behaviour, and found out that probing is able to distinguish them reasonably well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P1-sytvePZHsjYOG.png" /></figure><p>Different error types in free-form generation, exposed when resampled many times.</p><p>As of now, it seems like hallucinations are not going anywhere yet. Let’s hope that the work that is being done to address these issues will produce results and, perhaps, inspire further breakthroughs for AI-powered technologies in general.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b179d60af101" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nebius/eliminating-hallucinations-in-llm-training-are-we-there-yet-b179d60af101">Eliminating hallucinations in LLM training: are we there yet?</a> was originally published in <a href="https://medium.com/nebius">Nebius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How transformers, RNNs and SSMs are more alike than you think]]></title>
            <link>https://medium.com/nebius/how-transformers-rnns-and-ssms-are-more-alike-than-you-think-cd0f899893d8?source=rss-962f037330c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd0f899893d8</guid>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Stanislav Fedotov]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 11:10:05 GMT</pubDate>
            <atom:updated>2024-09-06T20:15:05.027Z</atom:updated>
            <content:encoded><![CDATA[<h4>By uncovering surprising links between seemingly unrelated LLM architectures, a way might be paved for effective idea exchange and boosting efficiency.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMKzXWqZQqE0bFtF80CxrQ.jpeg" /></figure><p>Even in the age of <a href="https://arxiv.org/pdf/2312.00752">Mamba</a> and other exciting linear RNNs and state space models (SSMs), transformer architectures still reign supreme as the backbone of LLMs. However, this might soon change: hybrid architectures such as <a href="https://arxiv.org/pdf/2403.19887v2">Jamba</a>, <a href="https://arxiv.org/pdf/2406.07522">Samba</a> and <a href="https://arxiv.org/pdf/2402.19427">Griffin</a> are quite promising. They are significantly more time- and memory-efficient than transformers, and their capabilities are not greatly diminished compared to attention-based LLMs.</p><p>At the same time, recent research has exposed deep connections between different architectural options: transformers, RNNs, SSMs and matrix mixers. This is very exciting because it allows for the transfer of ideas from one architecture to another. In this long read, we’ll mainly follow <a href="https://arxiv.org/pdf/2006.16236">Transformers, RNNs</a> and <a href="https://arxiv.org/pdf/2405.21060">Mamba 2</a>, getting elbows deep in algebra to understand how:</p><ul><li>Transformers may sometimes be RNNs (section 2),</li><li>State space models may hide inside the mask in the self-attention mechanism (section 4),</li><li>Mamba may sometimes be rewritten as masked self-attention (section 5).</li></ul><p>I find these connections quite fascinating, and I hope you, too, will appreciate them.</p><p>If you’re curious to learn more about the architectural development of transformer alternatives, please feel free to check <a href="https://medium.com/nebius/transformer-alternatives-in-2024-06cd3d91d42b">my separate post about them</a>.</p><h3>Masked self-attention in LLMs: a reminder</h3><p>A classic LLM self-attention layer looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*flqO2WEAHdDTUTpj.png" /></figure><p>Or, in more detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GRyC62nIR9g6lj3z.png" /></figure><p>Let’s briefly recall what happens here:</p><ul><li>We multiply the matrices <em>Q</em> of queries and <em>K</em> of keys. The product is an <em>L </em>× <em>L</em> matrix of scalar products of queries and keys.</li><li>We normalize the resulting matrix.</li><li>Then, we multiply it elementwise on the <em>L </em>× <em>L</em> <strong>attention mask</strong>. The picture shows the default <strong>causal mask</strong> — the 0–1 matrix on the left. It zeroes products (earlier query, later key), preventing attention from “looking into the future.”</li><li>Then, we take softmax.</li><li>Finally, we multiply the attention weights (let’s denote this matrix by <em>A</em>) on the values <em>V</em>; the <em>t-</em>th row of the output is:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KfYrEj74A_aSZmVI.png" /></figure><p>Thus, the<em> i-</em>th value is taken with the “attention weight of the <em>t</em>-th query for the <em>i</em>-th key.”</p><p>Many design choices in this architecture may be altered. Let’s explore some possible changes.</p><h3>Linearized attention</h3><p>Softmax in the attention formula ensures that the values are mixed with positive coefficients that sum to 1. This is good because it keeps some of the statistics intact, but it is very restricting; no term would escape its brackets, even if we would love to play with associativity like <em>(QK</em><strong><em>ᵀ</em></strong><em>)V = Q(K</em><strong><em>ᵀ</em></strong><em>V)</em>. Why do we need associativity, you ask? The thing is that changing the order of multiplication can drastically influence the complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tuiwFJ1IG_7DlEMb.png" /></figure><ul><li>In the left formula, we need to calculate an <em>L × L</em> matrix, which gives <em>O(L²d)</em> complexity cost and <em>O(L²)</em> memory cost if we allow this matrix to manifest fully in memory.</li><li>In the right formula, we need to calculate a <em>d</em> <em>× d </em>matrix, which gives <em>O(Ld²)</em> complexity cost and <em>O(d²)</em> memory cost if we allow this matrix to manifest fully in memory.</li></ul><p>Thus, as context length grows, the first formula becomes more costly than the second one and ultimately becomes prohibitively expensive.</p><p>So, you know what? Let’s crack this softmax open! Let’s write down the formula with the softmax in a bit more detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RbamVadJDQCgrqDC.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wDLxNF2mWJMZ0s9u.png" /></figure><p>is softmax.</p><p>The most inconvenient thing here is the exponent; we just can’t take anything out of it. Let’s just erase it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QBOysgti8mMaVT8f.png" /></figure><p>Note that the normalizer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yB9HHeScnAyODwMZ.png" /></figure><p>vanished.</p><p>The problem with this formula is that <em>q</em>ₜ​<em>k</em>ₛ<strong><em>ᵀ </em></strong>is not guaranteed to be positive, so we may end up mixing the values with different-sign coefficients (which is counterintuitive); and even worse, the denominator may vanish, breaking everything. We may add a “good” elementwise function <em>ϕ</em> (a kernel) to mitigate it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SI60gO9Jf0qjp23v.png" /></figure><p>The original work suggested <em>ϕ(x) = 1 + elu(x)</em>.</p><p>This variation of the attention mechanism is called <strong>linearized attention</strong>. And the good thing is that we can now play with associativity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2cGIT-R4Qpb5Sm6Y.png" /></figure><p><strong>A word of caution</strong>. The relations between <em>M, K</em><strong><em>ᵀ</em></strong><em> </em>and <em>V</em> in the brackets are now quite complex and are not expressed through just ordinary and elementwise matrix products. We’ll discuss this computational block in more detail in the next section.</p><p>Now if <em>M</em> is the causal mask with 1 on the diagonal and below and 0 above the diagonal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3L1P3YFHaQwARU-p.png" /></figure><p>then everything becomes even simpler:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LZjGGWR_vvtZ1ZCZ.png" /></figure><p>And this can be calculated in a very simple, <em>recurrent</em> way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a_pPEJmviNWuu8qS.png" /></figure><p>I think you won’t be surprised to learn that the ICML 2020 paper where linearized attention was first suggested is called <a href="https://arxiv.org/pdf/2006.16236">Transformers are RNNs</a>. Note that we have two hidden states here: a vector <em>z</em>ₜ​​ and a <em>matrix</em> <em>h</em>ₜ​ (<em>ϕ</em>(<em>k</em>ₜ​​)<strong><em>ᵀ</em></strong><em>v</em>ₜ​​ is column⋅row, so it’s a <em>d </em>× <em>d</em> matrix). In recent papers, linearized attention is often presented in an even simpler, distilled way, with no <em>ϕ</em> and no denominator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WnU2I3rLTTI_Sp1U.png" /></figure><p>Linearized attention has two important benefits:</p><ul><li>As a recurrent mechanism, it has linear complexity at inference time with respect to the sequence length <em>L.</em></li><li>As a transformer model, it can be efficiently trained in a parallel way.</li></ul><p>At this point, you probably have a pressing question: if linearized attention is so cool, why don’t we see it in every LLM and why do we still complain about attention’s quadratic complexity? Alas, linearized attention-based LLMs are less stable during training and reach somewhat lower capability than standard self-attention. It looks as if less information can be squeezed through the fixed‑<em>d</em>×<em>d</em>‑shaped bottleneck than through the adaptable <em>L </em>× <em>L</em>one. You can check the experiment results in <a href="https://manifestai.com/articles/linear-transformers-are-faster/">this article at Manifest AI</a>, for example.</p><p><strong>Further reading.</strong> The idea that RNNs and linearized attention are related is rediscovered and revisited in many recent works. Moreover, it’s becoming common in such papers to have a matrix hidden state that is updated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KEwdQjht2-MW-pnq.png" /></figure><p>where <em>k</em>ₜ and <em>v</em>ₜ​ are a “key” and a “value” of sort, with the output of an RNN layer being something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TtpVugP3Dl3ikLmw.png" /></figure><p>which boils down to linear attention.</p><p>As examples, I would suggest checking these two papers:</p><ul><li><a href="https://arxiv.org/pdf/2405.04517">xLSTM</a> — a May 2024 paper suggesting a development of the renowned LSTM recurrent architecture. Its mLSTM block features a matrix hidden state, which is updated in the already familiar way:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lwCsMHLeFVPTZO2m.png" /></figure><p>and is further multiplied on a “query” to obtain the output. (The paper’s linear algebra setup is transposed to ours: queries, keys and values are columns, not rows; hence the odd order in <em>v</em>ₜ<em>k</em>ₜ<strong><em>ᵀ</em></strong>​.)</p><ul><li><a href="https://arxiv.org/pdf/2407.04620">Learning to (learn at test time)</a>, emerging in July 2024, is another RNN architecture with a matrix hidden state and a very peculiar semantics: it is the parameter <em>W</em> of a function that is optimized by gradient descent as we iterate over <em>t</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*jEseLvN_ssbgI6rg.png" /></figure><p>Here, everything is also transposed, so the order is odd again. The math is more complicated than <em>W</em>ₜ = <em>W</em>ₜ₋₁​ + <em>v</em>ₜ <em>k</em>ₜ<strong><em>ᵀ</em></strong>​, but may be simplified to it.</p><h3>Exploring attention masks</h3><p>Now that we have simplified the mask attention mechanism, we can start developing it again. And there is an obvious room for experiments: choosing a different lower triangular (never look into the future) mask <em>M</em> instead of the ascetic 0–1 causal mask. But first, we need to deal with the emerging inefficiency.</p><p>In the previous section, we were actually very lucky to work with a simple 0–1 causal mask <em>M</em>. In general, the recurrent trick doesn’t work anymore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8KuTyOAfyK-c3qcS.png" /></figure><p>The coefficients <em>m</em>ₜ​​ₛ are different now, and there’ll be no recurrent formula relating <em>y₃</em> to <em>y₂</em>​. Thus, for each <em>t,</em> we’ll have to compute the sum from scratch, making the complexity asymptotic quadratic by <em>L</em> again instead of linear.</p><p>The answer is that we won’t use just any masks <em>M</em>, only special, “good” ones. Namely, the ones that can be quickly multiplied (not elementwise!) on other matrices. To see how we can benefit from this property, let’s understand how to calculate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EGalzfyA9Jku8jBD.png" /></figure><p>efficiently. First, let’s clarify what’s happening here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eOA_Yctgy4II4hpm.png" /></figure><p>If we descend to the individual index level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CTFNPGKb8oKJu1J9.png" /></figure><p>For the further discussion, it will be useful for us to color indices instead of blocks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oeUt-vr-pgvVz2lX.png" /></figure><p>Now, we are ready to formulate the four-step algorithm:</p><p><strong>Step 1</strong>. Take <em>K</em> and <em>V</em> and create a three-dimensional tensor <em>Z</em> with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D-VxGzJd2py5GJwZ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mANVdqYj6JMmJVjV.png" /></figure><p>(Each axis is marked with its length.) This step takes <em>O(Ld²)</em> time and memory.</p><p>Note that if we sum this tensor over the magenta axis <em>t</em>, we’ll get the product <em>K</em><strong><em>ᵀ</em></strong><em>V</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MM0BABIgM1cWq67x.png" /></figure><p><strong>Step 2.</strong> Now, we multiply <em>M</em> on this tensor (not elementwise!) in such a way that <em>M</em> is multiplied on each “column” of <em>Z</em> along the magenta axis <em>t</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oCECaycuuggeQ96T.jpeg" /></figure><p>This gives us exactly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YqmQVEAqvw-jxjjy.png" /></figure><p>Let’s denote the result by <em>H</em>. Now, it’s only left to multiply everything on <em>q,</em>which will be done in two more steps.</p><p><strong>Step 3a.</strong> Take <em>Q</em> and multiply elementwise on each <em>j </em>= const layer of <em>H</em>:​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s6Q_7yVzJ9GBSeWH.jpeg" /></figure><p>This results in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cd5iFvUph5BVOZ4k.png" /></figure><p>This step requires <em>O(Ld²)</em> time and memory.</p><p><strong>Step 3b.</strong> Sum the resulting tensor along the <em>i</em> axis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nh266Pc1FHcUkaMz.jpeg" /></figure><p>This step also requires <em>O(Ld²)</em> time and memory. And we obtain exactly the thing we need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3eQddHVXPxXIgxJc.png" /></figure><p>The most crucial step is the second one, and we deliberately omitted its complexity analysis. A naïve estimate is:</p><ul><li><em>O(L²)</em> for each matrix multiplication,</li><li>Repeating it <em>d²</em> times,</li></ul><p>So it’s a whopping <em>O(L²d²)</em>. But we will take not just any <em>M</em>. We will take <em>M</em>such that <strong>the complexity of multiplying </strong><em>M</em><strong> on a vector is </strong><em>O(RL)</em><strong> for some constant (and not very large) </strong><em>R</em><strong>.</strong></p><p>For example, if <em>M</em> is the 0–1 causal matrix, multiplication on it boils down to computing the cumulative sums, and it is done in <em>O(L)</em> time. But there are many more options for structured matrices with fast vector multiplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F3GecUCnklEPk3NG.png" /></figure><p>In the next section, we’ll discuss one of such matrix types — semiseparable matrices, which will turn out to be tightly connected with state space models.</p><h3>Semiseparable matrices and state space models</h3><p>Let’s recall that (discretized) <strong>\textbf{state space models}</strong> (SSM) are a class of sequential models connecting 11-dimensional input <em>x</em>ₜ, <em>r</em>-dimensional hidden state <em>h</em>ₜ, and 11-dimensial output <em>u</em>ₜ​ in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M7AbxDrKtuBhMV9H.png" /></figure><p>So, in the discretized form, it’s just a fancy linear RNN with a skip connection. Moreover, for the rest of the story, we’ll even forget about skip connections by setting <em>D</em>ₜ <em>= 0.</em></p><p>Now, let’s write our SSM as a single matrix multiplication</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LDugkmOaN7JtbiK3.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6eYXropTlIXrCjcw.png" /></figure><p>So, <em>M</em> is lower triangular, just like the attention masks we discussed earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pXZn9TAHs205OtCQ.png" /></figure><p>This type of matrix comes with a great boon:</p><p>An <em>L </em>× <em>L</em> lower triangular matrix whose elements may be presented in this way can be stored using <em>O(rL)</em> memory and has a matrix-vector multiplication complexity of <em>O(rL)</em> instead of the default <em>O(L²)</em> (see <a href="https://arxiv.org/pdf/2302.04515">this paper</a>for details).</p><p>This means that every state space model gives rise to a structured attention mask <em>M,</em> which can be used in an efficient transformer model with linearized attention.</p><p>The curious thing, though, is that a semiseparable matrix <em>M</em> is already quite complex and expressive, even without all the query-key-value machinery around it. Moreover, it may itself be a masked attention mechanism. We’ll see this in the next section.</p><h3>State apace suality</h3><p>Here, we finally arrive at one of the central results of the <a href="https://arxiv.org/pdf/2405.21060">Mamba 2</a> paper.</p><p>Let’s again consider <em>y = Mu</em>, where <em>u = u (x)</em> is a function of the inputs and MM is a separable matrix. Moreover, let’s consider a very special case where each <em>A</em>ₜ​ is a scalar matrix: <em>A</em>ₜ = <em>a</em>ₜ<em>I</em>. Then the formulas become especially simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gUAP6NC1g4gnbE84.png" /></figure><p>Note that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mQ7iVNhik8aN39KE.png" /></figure><p>is just a number. Moreover, we can stack <em>C</em><strong><em>ᵢ​</em></strong> and <em>B</em><strong><em>ᵢ​</em></strong> in matrices <em>B</em> and <em>C</em> such that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uawgmCfjK0IEpOyU.png" /></figure><p>Now we’ll also need the matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_xfz3By7Q9oR1D5U.png" /></figure><p>Then it’s easy to check that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*grlP3Q1Ty1FcWAaZ.png" /></figure><p>Have we seen this somewhere? Indeed! It’s masked attention with:</p><ul><li><em>G</em> for the mask,</li><li><em>C</em> for <em>Q</em>, the query matrix,</li><li><em>B</em> for <em>K</em><strong><em>ᵀ</em></strong>, the transposed key matrix,</li><li>for <em>V</em>, the value matrix.</li></ul><p>In classic SSMs, <em>B</em> and <em>C</em> are constants, but Mamba made them data-dependent, reinforcing the alignment. This correspondence between specific state space models and masked attention was introduced in the Mamba 2 paper as <strong>state space duality.</strong></p><p><strong>Further reading.</strong> The idea of using matrix mixers instead of more sophisticated architectures is not new, with one of the notable early examples being <a href="https://arxiv.org/pdf/2105.01601">MLP-Mixer,</a> which employed MLPs instead of convolution or attention for spatial mixing in CV tasks.</p><p>Although current research is mostly focused on LLMs, there are also several papers proposing non-transformer, matrix mixture architectures for encoder models. Examples include:</p><ul><li><a href="https://arxiv.org/pdf/2105.03824">FNet</a> from Google research with matrix mixer <em>M</em> based on Fourier transform,</li><li><a href="https://arxiv.org/pdf/2407.09941">Hydra</a>, which, among other ideas, proposed an adaptation of semiseparable matrices for non-causal (non-triangular) working mode.</li></ul><p>As always, I encourage you to check out our <a href="https://ai-dt.school/generative-ai/">Practical Generative AI</a> course, where the discussions often serve as a source of knowledge and inspiration for posts like this one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd0f899893d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nebius/how-transformers-rnns-and-ssms-are-more-alike-than-you-think-cd0f899893d8">How transformers, RNNs and SSMs are more alike than you think</a> was originally published in <a href="https://medium.com/nebius">Nebius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mixtures of Experts and scaling laws]]></title>
            <link>https://medium.com/nebius/mixtures-of-experts-and-scaling-laws-431dbc199872?source=rss-962f037330c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/431dbc199872</guid>
            <category><![CDATA[mixture-of-experts]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Stanislav Fedotov]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 09:44:26 GMT</pubDate>
            <atom:updated>2024-08-13T09:44:26.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26wOUwWWCAsk2way7KSvXw.png" /></figure><p>Mixture of Experts (MoE) has become popular as an efficiency-boosting architectural component for LLMs. In this blog post, we’ll explore the steps researchers have taken on the road toward the perfect mixture of experts.</p><p>MoE has been used in models like Mixtral, DeepSeek-V2, Qwen2–57B-A14B, and Jamba. However, like any architectural component, it has hyperparameters — total number of experts, number of active experts, granularity — that can affect the final model quality.</p><h3>MoE reminder</h3><p>In the world of GPU- and data-intensive LLMs, it’s important to find balance between various precious resources. For example, if we want an LLM to excel at a wide range of tasks, this is enabled by increasing the number of parameters, which in turn makes inference (as well as training) more compute-hungry.</p><p>MoE emerged as a way to create an LLM that is large and capable but somewhat less demanding at the inference stage. MoE suggests having several (e.g., 8) independent versions of a Feedforward block (FFN) — “experts” — and a router that decides which (e.g., 2) of these experts are used for each particular token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pEqXMLo3eiSbelfk.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/2101.03961">Switch Transformers by Google</a></figcaption></figure><p>You might ask, “Why just FFN, and not self-attention as well?” Self-attention is too complex, and FFN blocks usually contain more than half of all the LLM parameters.</p><p>The first LLM with MoE was <a href="https://arxiv.org/pdf/2401.04088">Mixtral-8×7B</a> (read “8 experts with a 7B base model”), created from <a href="https://arxiv.org/pdf/2310.06825">Mistral-7B</a> by spawning 8 copies of each FFN block of Mistral and adding a routing mechanism that chooses 2 experts for each token. Compared to the 7B parameters of Mistral, it:</p><ul><li>has 47B parameters and was able to compete with 70B models at the time of its creation, but</li><li>uses only 13B active parameters, making it more efficient than similarly-sized counterparts.</li></ul><p>Mixtral calculated expert weights like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8TB5o6PCINM76vPy.png" /><figcaption><em>Source: </em><a href="https://huggingface.co/blog/moe"><em>Hugging Face</em></a></figcaption></figure><p>With the final output being equal to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CH5NkPFaX0dU4w4ByZ7DKw.jpeg" /></figure><p>Note the random summand in 𝐻(𝑥)<em>ᵢ</em> which works as a regularizer for training stabilization.</p><p>This only works well if the router is balanced, meaning it doesn’t favor or disregard certain experts. Otherwise, efficiency can be hindered instead of improved. Special “hacks,” including an auxiliary balancing loss function, are used to keep everything running properly. Moreover, given the router assignment for a current token, Mixtral’s MoE mechanism tries to divide an incoming batch into almost equal parts with overhead not greater than the pre-set capacity factor (usually around 1–1.25):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*Ywnd3y6r6lFBxv4b.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/2101.03961">Switch Transformers by Google</a></figcaption></figure><p>Illustration of token routing dynamics. Each expert processes a fixed batch-size of tokens modulated by the capacity factor. Each token is routed to the expert with the highest router probability, but each expert has a fixed batch size of (total tokens/num experts) × capacity factor. If the tokens are unevenly dispatched, then certain experts will overflow (denoted by dotted red lines), resulting in these tokens not being processed by this layer. A larger capacity factor alleviates this overflow issue but also increases computation and communication costs (depicted by padded white/empty slots).</p><p>Check out the Hugging Face post mentioned above for more details.</p><p><strong>Note:</strong> MoE LLMs are also referred to as <em>sparse,</em> while non-MoE models are called <em>dense</em> by comparison.</p><h3>We need more experts</h3><p>Mixtral had only 8 experts, but later models went much further.</p><p>For example, <a href="https://arxiv.org/pdf/2405.04434">DeepSeek-V2</a> has 2 shared experts and 160 routed experts, of which 6 are selected for each token. With 236B total parameters, it has only 21B activated for each token. Shared experts are always invoked; they are said to capture common knowledge across varying contexts. Routed experts are numerous, and some of them turn out to be highly specialized.</p><p>The behavior of MoE LLMs with a growing number of experts has been studied in several recent works, and there are good reasons to believe that having many experts is beneficial. I’ll mention two works studying related empirical <em>scaling laws:</em></p><ol><li><strong>Unified scaling laws for routed language models</strong> This paper <a href="https://arxiv.org/pdf/2202.01169">showed</a> that the validation loss tends to improve with a growing expert count:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JktNGXkUPh-ZO47K.jpg" /></figure><p>The authors also studied the <em>effective parameter count</em>. For example, cB (c billions) is the efficient parameter count of Mixtral-8×7B if a hypothetical Mistral-cB would give the same quality as Mixtral. The researchers found that the gain in effective parameter count diminishes with growing base model size: if Mistral had 1T parameters instead of 7B, creating Mixtral-8×1T out of it wouldn’t improve the quality (<a href="https://arxiv.org/pdf/2202.01169">same source</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*moDc4SE1jYp6CTXE.jpg" /></figure><p>(Here, S-BASE, RL-R, and Hash stand for different ways of distributing a batch between experts more evenly).</p><p><strong>The takeaway:</strong> Having more experts is beneficial, although the gain diminishes with increasing base model size.</p><p>This approach may be criticized for using the same training dataset for all model sizes; this will be addressed in the next paper.</p><p>2. The next paper, <strong>Scaling laws for a fine-grained mixture of experts</strong>, <a href="https://arxiv.org/pdf/2402.07871">takes</a>two important steps forward. First, it seeks optimal training dataset sizes for all the models. Second, it introduces the idea of expert <em>granularity.</em> Imagine again Mistral-7B, which we are turning into a MoE model. Initially, it becomes Mixtral-8×7B with 8 experts, each outputting <em>d</em>-dimensional vectors. Now, let’s split each expert into <em>G</em> smaller experts that output vectors of dimension <em>d/G:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xQD0nYmHj0YfaQb_.png" /></figure><p>If G = 2, each original expert becomes two fine-grained experts. Moreover, the router will now choose not 2 out of 8 experts but 4 out of 16.</p><p>Now, the paper studies scaling laws as the balancing of the following parameters:</p><ul><li>Total training compute in FLOPs (which depends on both model size and dataset size),</li><li>Base model size,</li><li>Number of experts,</li><li>Expert granularity,</li><li>Validation loss.</li></ul><p>Granularity turns out to be an important hyperparameter. As base model size increases, it seems beneficial to increase granularity (here, <em>N</em> is the model size and <em>D</em> is the training dataset size in tokens):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C-zv3U5YlDmSWLcp.jpg" /><figcaption>Source: <a href="https://arxiv.org/pdf/2402.07871">Scaling laws for fine-grained mixture of experts</a></figcaption></figure><p>It’s also advantageous to increase the number of experts (same source):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nbNGxj80h_dAGXER.png" /></figure><p>The problem is that increasing the number of experts and granularity may eventually hinder model efficiency, as seen in this plot (same source):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iIuI42vAY98coRnx.jpg" /></figure><p>Here, for G = 16, the routing cost dominates gains from granularity. Overcomplicated routing will also make things slower at inference.</p><p><strong>The takeaway:</strong> If we increase granularity in a timely manner, MoE steadily improves quality until routing complexity interferes.</p><h3>What if we have a million tiny experts?</h3><p>From the previous paper’s perspective, model quality may improve infinitely as we increase the number of experts and the granularity toward having something like 1,000,000 small experts — if only the routing process is optimized.</p><p>A way to optimize it is suggested in the <strong>Mixture of a Million Experts</strong> <a href="https://arxiv.org/pdf/2407.04153">paper</a>. Imagine that we have many small experts 𝑒<em>ᵢ</em>, each having a fixed key 𝑘<em>ᵢ​</em> (just a constant vector). Let 𝐾<em> </em>be the number of experts we want to use for each token.</p><p>The MoE layer in this paper works differently compared to how it does in Mixtral:</p><ol><li>Calculate a query vector 𝑞(𝑥),</li><li>Calculate the scalar products 𝑞(𝑥)<em>ᵀ </em>𝑘<em>ᵢ</em>,</li><li>Find<em> </em>𝐾 maximal 𝑞(𝑥)<em>ᵀ </em>𝑘<em>ᵢ</em>​,</li><li>Only for these experts, calculate router scores: 𝑔<em>ᵢ</em>​(𝑥) = 𝑠 (𝑞(𝑥)<em>ᵀ </em>𝑘<em>ᵢ</em>),</li><li>Finally, the output is:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*waSU7cQZ1YNns_GX.png" /></figure><p>The actual routing closely resembles a nearest neighbor search in a vector database. For that, we have efficient algorithms, but since we need to do it for every token, it can be good to optimize it even further.</p><p>The authors suggest using <em>product keys,</em> that is, taking 𝑘<em>ᵢ </em>= (𝑐ᵢ, 𝑐’<em>ᵢ</em>), a concatenation of two keys of half the dimension of 𝑘<em>ᵢ</em>. For a million experts, it’s enough to have only a thousand different 𝑐<em>ᵢ</em>​. Thus, instead of doing the nearest neighbor search in a 1,000,000-size database, we only need to do it twice for two 1,000-size databases, which is much more efficient.</p><p>The authors go as far as to suggest setting experts 𝑒<em>ᵢ </em>to be one-dimensional (with scalar output). To make the MoE more expressive, they make them multi-head: 𝑞ₕ(𝑥),</p><ol><li>Calculate 𝐻 independent query vectors 𝑞ₕ(𝑥),</li><li>Calculate the scalar products 𝑞ₕ(𝑥)<em>ᵀ</em>𝑘<em>ᵢ</em>,</li><li>For each ℎ, find its own set of 𝐾 maximal 𝑞<em>ᵢ</em>(𝑥)<em>ᵀ </em>𝑘<em>ᵢ</em>,</li><li>Only for these experts, calculate router scores: <em>𝑔</em>ₕ,<em>ᵢ</em>(𝑥) = 𝑠(𝑞ₕ(𝑥)<em>ᵀ </em>𝑘<em>ᵢ</em>),</li><li>Finally, the output is:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oz_RrqFhW_V6u7ZO.png" /></figure><p>Evaluation results may be summarized in the following plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ic0up7n_7q-yIzby.jpg" /><figcaption>Source: <a href="https://arxiv.org/pdf/2407.04153">Mixture of a Million Experts</a></figcaption></figure><p>Using their method, called PEER, the authors are able to achieve a stable improvement in perplexity as <em>N</em> (the total total number of tiny experts) increases up to 102⁴².</p><p><strong>The takeaway:</strong> With optimized routing, MoE steadily provides quality improvement.</p><h3>When many experts can be of use: A case of lifelong learning</h3><p>If you’re capable of training an LLM, you probably want to create a new one every year or so, with new architectural perks, etc. However, between episodes of training from scratch, you may want to update your existing LLM with some new data — to adapt it to a new data distribution. Simply continuing the previous training process may sometimes cause catastrophic forgetting. LoRA is not very capable of grasping new knowledge. So what should you do?</p><p>The <strong>Lifelong language pretraining with distribution-specialized experts</strong>paper <a href="https://arxiv.org/pdf/2305.12281">suggests</a> freezing the existing parts of the LLM and augmenting it with new experts and gating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wiuJ8aEOLVCf9Bdt.jpg" /></figure><p>The results are somewhat mixed, but overall, the idea is interesting.</p><p>This article was inspired by discussions at the paperwatch meetings of the Practical Generative AI course, which is run by the School of AI and Data Technologies. If you’re interested in studying LLMs and other generative models, their internal workings and applications, check out <a href="https://ai-dt.school/generative-ai/">our program</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=431dbc199872" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nebius/mixtures-of-experts-and-scaling-laws-431dbc199872">Mixtures of Experts and scaling laws</a> was originally published in <a href="https://medium.com/nebius">Nebius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fundamentals of LoRA and low-rank fine-tuning]]></title>
            <link>https://medium.com/nebius/fundamentals-of-lora-and-low-rank-fine-tuning-e748f2f1255d?source=rss-962f037330c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e748f2f1255d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[study]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Stanislav Fedotov]]></dc:creator>
            <pubDate>Mon, 17 Jun 2024 10:52:31 GMT</pubDate>
            <atom:updated>2024-06-21T07:00:26.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzHeRdV69t2vPu2FKJdY6w.jpeg" /></figure><p>In the next installment of our series of deep technical articles on AI research, let’s switch our attention to the famous LoRA, a low-rank adaptation technique.</p><h3>1. Introduction</h3><p>It’s easy to understand why we resort to parameter-efficient fine-tuning of LLMs: fully training them is an extremely costly process.</p><p>However, it turns out that a strong pre-trained model doesn’t require many parameters to be adapted for a specific task! This was known as early as 2020 when the authors of <a href="https://arxiv.org/pdf/2012.13255.pdf">Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning</a> ran several experiments with encoder-only models of the BERT and RoBERTa classes to explore the ‘intrinsic dimensions’ of various problems.</p><p>Specifically, they analyzed several tasks, and for each, they determined <em>d</em>₉₀​: the minimum dimension <em>d</em> for which fine-tuning in a <em>d</em>-dimensional subspace gives more than 90 percent of full fine-tuning quality. Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v-BGTUVttmPwIcsM.png" /></figure><p>The dashed line represents the <em>d</em>₉₀​ value, and you can see that in many cases, it can be achieved with a <em>d</em> significantly smaller than <em>D</em>. Note, by the way, that the horizontal axis is logarithmic.</p><p>As LLMs matured, several low-parameter fine-tuning techniques emerged, and the most influential of them is <a href="https://arxiv.org/pdf/2106.09685">LoRA</a> — the abbreviation comes from low-rank adaptation.</p><p>In this long read, we will discuss LoRA and some of its modifications. Namely, I will share with you:</p><ul><li>What is rank from a math point of view, and how to wrap your intuition around it.</li><li>What exactly we mean by fine-tuning a model in a low-dimensional subspace.</li><li>Why LoRA updates come in a two-matrix-product form.</li><li>Which exciting developments arose around LoRA recently.</li></ul><h3>2. A few words about rank</h3><p>There are many kinds of layers inside LLMs, but in the end their parameters are stored in matrices (luckily, you don’t often encounter tensors in LLMs). And each matrix has a characteristic called <strong>rank</strong>. Usually, rank is defined like this:</p><blockquote>The rank of a matrix A is the maximum number of linearly independent columns (or rows) that can be found in the matrix. (You’ll get the same number if you take rows instead of columns).</blockquote><p>While this definition is correct, my experience shows it’s not easy to use. So, let’s consider an equivalent one.</p><p>A real matrix <em>A</em> of size <em>M </em>× <em>N</em> is usually more than just a table filled with numbers; it can represent a variety of algebraic entities. Importantly for our discussion, it can represent a linear transformation <em>F</em>: ℝ<em>ᴺ</em> → ℝ<em>ᴹ</em> mapping from an <em>N</em>-dimensional space to an <em>M</em>-dimensional space (mind the order!). My favorite way to characterize rank is:</p><blockquote>The rank of a matrix A is <em>dim⁡ Im</em>(Fᴬ), the dimension of the image of Fᴬ.</blockquote><p>For example, if <em>A</em> is 3 × 2, it represents a linear transformation ℝ² → ℝ³, and its rank could be 2 (top picture), or 1 (bottom picture), or even 0 if the image is zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*evXupQlrInoMF5Ia.jpg" /></figure><p>While I won’t formally prove the equivalence of these two definitions here, let me remind you that the columns of a matrix of a linear transformation are precisely the images of the standard basis vectors. Here is an example of a 4 × 3 matrix corresponding to a linear map ℝ³ → ℝ⁴:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZ-YGW21y8p_r5VWacF9mg.png" /></figure><p>If you need a basis for the image of <em>Fᴬ</em>​, you can take a maximal linearly independent subset of <em>A</em>, such as <em>Ae</em>₁, <em>Ae</em>₂​. Thus, the rank is 2.</p><h3>3. Low-rank adaptation — LoRA</h3><p>The essence of LoRA is:</p><p><em>Let’s only do low-rank parameter updates.</em></p><p>To clarify, consider some weight matrix <em>W</em>, which is, of course, a matrix of some linear transformation <em>Fᵂ</em>: ℝ<em>ᴹ</em> → ℝ<em>ᴺ</em>. A low-dimensional update of <em>F</em>​<em>ᵂ</em> is a new transformation <em>G</em>:</p><p><em>G</em>(<em>x</em>) = <em>Fᵂ</em>(<em>x</em>)<em> + F </em>′(<em>x</em>),</p><p>where the image of <em>F </em>′ is low-dimensional.</p><p>Here is an example where <em>Fᵂ</em>: ℝ² → ℝ³ and <em>F </em>′ has a rank of 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iluk77ewEcKn1Y7Q_5vtLw.jpeg" /></figure><p>You see that adding <em>F </em>′ changes only what happens on the green line.</p><p>LoRA suggests the following:</p><ul><li>We freeze <em>Fᵂ</em>,</li><li>We only fine tune <em>F </em>′ and demand that the rank of its matrix <em>W </em>′ is ⩽ r, where <em>r </em>is a hyperparameter.</li></ul><p>The problem is that optimizing <em>W </em>′ over a subset is usually tricky, to say the least. Can we find a convenient parametrization for rank ⩽ <em>r</em> matrices? It turns out that yes, and for this purpose, we will revisit our dimension-of-the-image description of rank.</p><h3>4. Parametrizing a low-rank matrix</h3><p>Let’s take another look at our rank-1 example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h-glFYqbtqPtnyjA.jpg" /></figure><p>This transformation can be done in two stages:</p><ol><li>First, we map a 2d plane onto a line using a matrix <em>A</em> of shape 1 × 2.</li><li>Then, we embed this line into a 3d space using a matrix <em>B</em> of shape 3 × 1.</li></ol><p>Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wqX8X4O0wvCLmT_i.jpg" /></figure><p>Now, we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqWGtmdZh5ybz6BwfodIkA.jpeg" /></figure><p>or, in matrix terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zzh2TJLw5kWg1s3_85utpg.png" /></figure><p>In exactly the same way, we can demonstrate that any <em>M</em> × <em>N</em> matrix <em>W</em> of rank <em>r</em> can be decomposed as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0lhxXpCgqpbdTKVrvCpqg.png" /></figure><p>Moreover, if there is a decomposition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLLwLM4pvDP8dL77fnYDtg.png" /></figure><p>then rk<em>W </em>⩽ <em>s</em>. Note: the rank can be less if the ranks of <em>A</em> and <em>B</em> are less than <em>s</em>.</p><p>And that’s exactly what we do in LoRA. We decompose W′ = <em>BA</em> and train matrices <em>B</em> and <em>A </em>without any additional constraints!</p><p>Now, you should better understand what happens in this image (sourced from <a href="https://huggingface.co/blog/trl-peft">here</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V5ihUuuSOQ3ieWhf.jpg" /></figure><p>Now, we can explicitly calculate how much additional memory LoRA requires. For example, if the original <em>W</em> was 4096 × 4096, like in Mistral’s q_proj layer, and the LoRA rank is <em>r </em>= 8, then:</p><ul><li><em>A</em> is of shape 8 × 4096,</li><li><em>B</em> is of shape 4096 × 8,</li></ul><p>giving 8 ⋅ 4096 + 4096 ⋅ 8 = 65,5368 new parameters, which is only about 0.4% of the 4096 ⋅ 4096 parameters of <em>W</em>.</p><p>There is no general rule, but usually quite small values of <em>r</em> are used. It’s reasonable to go with 8, or 16, or, if you’re especially generous, with 64, although I wouldn’t start with it. Usually, all dense layers, except for the embedding layer, are fine-tuned, that is:</p><ul><li>Query, key and value projections (q_proj, k_proj, v_proj layers) and the output projection of the attention block (o_proj layers),</li><li>All the dense layers inside the Feedforward block.</li></ul><p>Often, a dropout layer is also added before <em>BA</em> with <em>p </em>= 0.1 or likewise small.</p><p>The one thing I would add is how we initialize <em>B</em> and <em>A</em>. We want to start fine-tuning from the pre-trained weights <em>W</em>, so <em>W </em>′ should initially be zero. It’s easy to do this by setting the initial <em>B</em> to zero, as depicted in the image above.</p><p>LoRA has proven itself a worthy companion for any LLM engineer and a default choice for fine-tuning tasks.</p><p>It has been observed, though, that LoRA often yields worse results than full fine-tuning. Of course, we could blame a lack of parameters, but there are additional inefficiencies in LoRA, which we’ll discuss in upcoming sections.</p><h4>4.1. Intrinsic dimensionality: experiment details</h4><p>I previously mentioned the paper <a href="https://arxiv.org/pdf/2012.13255.pdf">Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning</a>, which showcased that certain task can be successfully solved with low dimensional parameter updates. I skipped the details of the experiment setup, so I’ll briefly explain it now.</p><p>The LoRA update is expressed as:</p><p><em>W ↦ W + BA</em>,</p><p>where <em>Fᴀ</em>​ projects to an <em>r</em>-dimensional (low-dimensional) space, and <em>F</em>ʙ embeds the latter into the image space of <em>Fᵂ</em>.</p><p>What the authors of the Intrinsic Dimensionality paper did is:</p><ul><li>They took specially structured random <em>B</em> and froze it.</li><li>They then trained <em>A</em>.</li></ul><p>This means that for each experiment, they fixed a random subspace and trained the updates within it, while LoRA trains both the subspace (<em>B</em>) and the updates within it (<em>A</em>).</p><p>It’s interesting that we can get meaningful results even when making updates in a randomly selected subspace with a random frozen <em>B</em>. But of course, it’s much better to make them trainable.</p><h3>5. PiSSA: using SVD to do updates in a more meaningful subspace</h3><p>When we we implement LoRA, <em>B</em> evolves through stochastic gradient descent, allowing the subspace where the updates occur and, develop randomly. This raises the question: can we identify a ‘good’ starting subspace?</p><p>The answer might be yes. We have a good old method for identifying ‘meaningful’ subspaces, known as <strong>singular value decomposition</strong> (<strong>SVD</strong>). Let’s briefly revisit what it is.</p><p>By definition, a singular value decomposition (SVD) of a matrix <em>W</em> is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTwF50YsaZ3iiTSP3xm9mQ.png" /></figure><p>where:</p><ul><li><em>U</em> is orthogonal, meaning the columns <em>ui</em>​ of <em>U</em> are mutually orthogonal vectors of length 1: ⟨<em>u ᵢ</em>, <em>uⱼ</em>⟩ = 0 for <em>i</em> ≠ <em>j</em>, and |<em>u ᵢ</em>| = 1. (The same is true for rows of <em>U</em> because <em>U</em> is square).</li><li><em>V </em>is also orthogonal.</li><li>Σ = diag(<em>σ</em>₁, <em>σ</em>₂, …) is diagonal with <em>σ</em>₁ ⩾ <em>σ</em>₂ ⩾ … ⩾ 0. These <em>σᵢ </em>are known as the <strong>singular values</strong> of <em>W</em>. Just be aware that Σ is not always square; for example:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhK_f45Qu54pxy6fvQPolQ.png" /></figure><p>To move on, we need to tinker with matrices a bit. First, we can put <em>σᵢ</em> into the columns of <em>U</em> and the rows of <em>Vᵀ</em> (which are the transposed columns of <em>V</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7RNK1vEWV3RziVRn.jpg" /></figure><p>Next, we use the following matrix identity…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GNLYWy0xxRc9Ugy8.jpg" /></figure><p>…to reformulate SVD as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lfN5oUc_81BMSPyz.jpg" /></figure><p>Now, let’s recall that <em>σ</em>₁ ⩾ <em>σ</em>₂ ⩾ … ⩾ 0. Moreover, in most real cases, the singular values <em>σᵢ</em>​ decline rapidly, enabling us to select a reasonable <em>r</em> &lt; <em>M</em>, N such that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCpL0_M6spqvYLIsCty_9w.jpeg" /></figure><p>is significantly less than <em>σ</em>₁​. We can then suggest that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cN_dy6zalgCVlM1IKPmDA.jpeg" /></figure><p>encapsulates the meaningful components, while</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLWX_cfW3sjPAwnESVj9_Q.jpeg" /></figure><p>represents ‘noise’. Reapplying the green-and-blue matrix identity, we can depict it this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CwMw5JSxacKoomjd.jpg" /></figure><p>Here, the first part of the sum is meaningful and the second is ‘noise’. We can distill this further into:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caRB2WpdBa5wPIpQmSZNmA.png" /></figure><p>Here’s what we have here:</p><ul><li>The summand <em>BA </em>likely represents the ‘important’ part of the matrix.</li><li><em>A</em> is a projection to an <em>r</em>-dimensional space, while <em>B</em> embeds this space into the image space of <em>W</em> as the <em>r</em>-dimensional subspace <em>Sᵣ</em>.</li></ul><p><strong>Caution!</strong> When using SVD, we persuade ourselves that all the interesting things happen in <em>Sᵣ</em>​. However, this is not always true. The principal components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L41uSIzvlKNirOh4i1FVyA.jpeg" /></figure><p>are larger but not necessarily more interesting or useful. Sometimes, the finest details are the most important ones. However, SVD may give us a good starting point for training LoRA.</p><p>The <a href="https://arxiv.org/pdf/2404.02948.pdf">PiSSA</a> paper suggests exactly that. The authors take</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caRB2WpdBa5wPIpQmSZNmA.png" /></figure><p>as we did earlier and further fine-tune <em>A</em> and <em>B</em>. The results are nice; the authors claim to beat LoRA in their experiments, and they also show that PiSSA performs better than QLoRA in a quantization strategy when the base model is set to ‘nf4’ precision and frozen, while the adapters are trained using ‘bfloat16’ precision.</p><h3>6. DoRA: decoupling magnitude and direction updates</h3><p>The authors of <a href="https://arxiv.org/pdf/2402.09353">DoRA: Weight-Decomposed Low-Rank Adaptation</a> did an insightful analysis of magnitude and direction updates during full fine-tuning versus LoRA.</p><p>Consider the columns of the weight matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DlXaILiw5RiCm_yBfegjdQ.png" /></figure><p>As we remember, each w<em>ᵢ</em> is the image under <em>W</em> of the standard basis vector <em>eᵢ</em>​. During fine-tuning, the vectors w<em>ᵢ </em>change in both magnitude and direction. It’s curious to see that the patterns of these changes differ between full fine-tuning (FT) and LoRA. Let’s explore how. We decompose the matrix as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Wd6Ez1uIbg8PcXmlM-9lw.png" /></figure><p>where <em>m</em>, also denoted by ||<em>W</em>|| (<strong>magnitudes</strong>), is the vector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tX4W1T3DVJbqRakL-9uohg.png" /></figure><p>the fraction (<strong>directions</strong>) is the following matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pKTZ05WeqdDs99JannN_9w.png" /></figure><p>and ⊙ stands for a special kind of element-wise product.</p><p>Now, here’s an image illustrating the patterns of change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*59KCNjrHNPA-uiz6.jpg" /></figure><p>On the Δ<em>M</em> axis, we have MAE between ||W|| before and after fine-tuning. On the Δ<em>D</em> axis, we have mean (1 − cos⁡(⋅,⋅)) distance between</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uabcilsAHnhfdm93kPtdAw.jpeg" /></figure><p>before and after fine-tuning.</p><p>For LoRA, there is a notable positive correlation between Δ<em>D</em> and Δ<em>M</em>, while for full fine-tuning (FT), these values exhibit a weaker negative correlation. This hints that in LoRA, magnitudes and directions might become entangled in a suboptimal way. To address this, the authors of DORA suggest decoupling them during fine-tuning. Specifically, they update the weight matrix as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RJ7TMYqVOqteS0akODSwg.png" /></figure><p>where:</p><ul><li><em>W</em>₀ is the initial <em>W</em> before fine-tuning,</li><li><em>m</em> is a trainable magnitude vector, initialized as ||<em>W</em>₀||,</li><li><em>BA</em> is a low-rank LoRA summand with trainable matrices <em>A</em> and <em>B</em>,</li><li>Division by ||<em>W</em>₀ + <em>BA</em>|| means division of each column of <em>W</em>₀ + <em>BA</em> by its length.</li></ul><p>The method can be summarized in this table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2a7F9kTWgu20kQDM.jpg" /></figure><p>As you could see in the earlier plots, the correlation between magnitude and direction updates exhibits a weak negative correlation, similar to what we see in full fine-tuning. This correlation can be really important, as in experiments, DORA consistently outperformed LoRA (well, if +1 point in quality is enough for you).</p><p>This article was inspired by my experience of teaching linear algebra and by discussions at the paperwatch meetings of the Practical Generative AI course by School of AI and Data Technologies. If you’re interested in studying LLMs and other generative models, their internal workings and applications, check out our <a href="https://ai-dt.school/generative-ai/">program</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e748f2f1255d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nebius/fundamentals-of-lora-and-low-rank-fine-tuning-e748f2f1255d">Fundamentals of LoRA and low-rank fine-tuning</a> was originally published in <a href="https://medium.com/nebius">Nebius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformer alternatives in 2024]]></title>
            <link>https://medium.com/nebius/transformer-alternatives-in-2024-06cd3d91d42b?source=rss-962f037330c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/06cd3d91d42b</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[study]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Stanislav Fedotov]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 10:32:59 GMT</pubDate>
            <atom:updated>2024-06-17T10:50:56.008Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGRdqEgjJ_1bLkS1sSSJGQ.jpeg" /></figure><p>With this article, we are starting a new category on our blog, the one dedicated to AI research. Expect these posts to be very technical and insightful. The first one is about possible alternatives to the key component of the LLM architecture.</p><h3>1. Introduction</h3><p>Transformer models are cool, but they do have performance issues. In the classic setup, during the attention phase, each token must “attend” to every other token, leading to quadratic complexity. Moreover, to avoid recalculating all keys and values at each decoding step, they are stored in a key-value cache. These two factors make transformers punishingly expensive for processing long sequences.</p><p>There are several intrinsic approaches for addressing these issues. Some focus on making attention less compute-hungry. An example is Group-Query attention that proposes retaining only one attention head for keys and values, thus accelerating attention and reducing the kv-cache size. Others, like FlashAttention, seek to leverage hardware features and algorithmic advancements to make the attention mechanism more efficient without altering its core essence.</p><p>However, there is also research focused on entirely eliminating attention and its associated quadratic complexity. To date, the most successful attempts involve Linear (without nonlinearity in the recurrence) RNNs. Why are Linear RNNs advantageous?</p><ul><li>As RNNs, they are efficient at the inference stage: no need to consider the entire previous sequence, only the preceding step.</li><li>Thanks to the absence of nonlinearities, Linear RNNs can be reformulated as convolutions (see <a href="#0919">2.3</a>), which, with a mix of math, Fast Fourier Transforms, hardware considerations, and a bit of luck, allows for effective parallelization during training.</li><li>They can be linked to continuous-time state space models, opening up even more possibilities for improvement and analysis.</li></ul><p>So far, the pinnacles of this research are <a href="https://arxiv.org/pdf/2312.00752.pdf">Mamba</a>, <a href="https://arxiv.org/pdf/2402.19427.pdf">Griffin</a>, and the recent <a href="https://arxiv.org/pdf/2403.19887.pdf">Jamba</a> (see also the <a href="https://www.ai21.com/blog/announcing-jamba">blog post</a>). Jamba, for instance:</p><ul><li>Delivers three times the throughput on long contexts than Transformer-based models of comparable size.</li><li>Supports 140K contexts on a single GPU, whereas Mixtral can only fit 64K context.</li><li>Shows competitive quality on popular benchmarks with the Transformer-based models of its size.</li></ul><p>Sounds nice, does it?</p><p>In this long read, you will learn what design choices led to creation of these models.</p><h3>2. The main story: from RNNs to Mamba and beyond</h3><h4>2.1. Beyond attention: any ideas?</h4><p>A typical transformer-based LLM architecture looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*eP2OAAhxuuOnTfT2KdgGlw.jpeg" /><figcaption><a href="https://arxiv.org/pdf/2402.19427.pdf">Source</a></figcaption></figure><p>Attention contributes by propagating information across time, unlike the MLP block, which solely performs channel mixing.</p><p>We have other mechanisms for temporal propagation, namely:</p><ul><li>Convolutions. They are highly parallelizable, but capturing a long context requires a long kernel, and this will hinder its efficiency: too many trainable parameters in a kernel of a size of a typical transformer kv-cache. So, it is either no gain in comparison to transformers or restricted locality.</li><li>Recurrence. In theory, it allows to capture all the previous context while keeping the complexity linear. However, in practice, information can be lost along the way.</li></ul><p>Despite these drawbacks, the ideas behind today’s non-attention-based NLP models stem from different combinations of convolutional and recurrent principles.</p><p>And it all starts with a simple but unexpected thing: Linear RNNs are good.</p><h4>2.2. Linear RNNs are good</h4><p>The idea that something non-linear must come between linear layers lies in the foundation of deep learning. So, traditional RNNs operate as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpfghWyI-U_gRk6ZMTkJwA.png" /></figure><p>where <em>uₜ</em> is the input, <em>yₜ</em> is the output, <em>xₜ</em> is the hidden state, <em>g</em> is a nonlinearity, and <em>Duₜ</em> is a skip-connection. Okay; skip connections were not typical in the mid-2010s, but later on, we have learned to value them. Note that I deliberately omitted the bias terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*IH9eRh3EBRZcdUDDZLFrEQ.png" /></figure><p>Let’s call Linear RNN a network consisting of several (RNN + MLP) blocks, where <em>g</em> is set to identity in each of the recurrent layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*VeC1OEWVAcb-y4vlN4cc4Q.png" /></figure><p>You might scoff at such a network, but the authors of the <a href="https://arxiv.org/pdf/2303.06349.pdf">Resurrecting RNNs paper</a> demonstrate that it is quite expressive and can even be better than networks with tanh or ReLU for <em>g</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lX-HtEMFXGURzi6XhKkL5g.png" /></figure><p>It seems like it is enough to have nonlinearities in the MLP blocks.</p><h4>2.3. Time-parallel usage: Linear RNNs as convolutions</h4><p>Let’s consider the full pass of information through a Linear RNN:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EL98V_fLVLU2k14DbKy3A.png" /></figure><p>for a sequence <em>u₀, u₁, …</em> (where <em>u₀</em> = 0) this gives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMy-Vmjmt4swI8hz7_rh6A.png" /></figure><p>This can be interpreted as a convolution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhQlydED0jFgWVf38hG3lw.png" /></figure><p>where <em>L</em> is the potential max length of a sequence, <em>Duₖ</em> works as residue connection, and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gP9T7YLCJUKhaYeIWXZ_Gg.png" /></figure><p>is the convolution kernel.</p><p>This convolution is parameter-efficient: the number of its trainable parameters does not scale with <em>L</em>. But still, the convolution is very, very long, so we need several hacks to make it work efficiently.</p><p><strong>Hack 1. Matrix <em>A</em> should be simple</strong></p><p>Often, it is diagonal.</p><p>It can be <a href="https://arxiv.org/pdf/2303.06349.pdf">complex diagonal</a> as the Linear Recurrent Unit (LRU) with its intricate parametrization of <em>A</em> = diag (λ) and additional normalization <em>γ</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGLd6WxSnlr8cJX8brNOBg.png" /><figcaption><a href="https://arxiv.org/pdf/2303.06349.pdf">Source</a></figcaption></figure><p>The paper has an elegant mathematical explanation for this parametrization.</p><p>It can also be <a href="https://arxiv.org/pdf/2111.00396.pdf">diagonal + low rank</a> or even non-trainable. If a matrix is sufficiently simple (quasiseparable, see <a href="https://arxiv.org/pdf/1602.01246.pdf">here</a>), then the kernel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*443i3xBaddOmA7liiDnKZg.png" /></figure><p>can be computed in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WinZ0gvNx-3NwG1kGXV8fQ.png" /></figure><p>time and memory for some <em>q</em>, where <em>d</em> is the dimension of the implicit states <em>xₖ</em>. This is at least faster than full attention in a transformer.</p><p>I would like to add that the choice of parametrization and/or initialization of A is determined not only by our desire to compute convolutions efficiently. It is also crucial to ensure that a Linear RNN in its recurrent mode captures the previous context well.</p><p>Here is a nice way of thinking about it: memorizing ability equals the ability to compress information about the previous context in a vector of a given dimension. Let’s make a step from discrete sequences to functions <em>f(t)</em> of variable <em>t</em>. We know a good way of vectorizing a function: Fourier analysis. A development of this approach allowed the authors of the <a href="https://arxiv.org/pdf/2008.07669.pdf">HiPPO paper</a> to come up with an influential way of initializing the matrix A for state space models, a continuous-time version of Linear RNNs, which you’ll encounter quite soon.</p><p><strong>Hack 2. You need to know how to speed up a convolution</strong></p><p>A must-have improvement is using the convolution theorem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4WxWNWKPnzqVesPy6Mgbg.png" /></figure><p>connecting convolution and pointwise multiplication (⊙) via Fast Fourier Transform <em>F</em>. This allows to decrease the complexity of convolution from <em>O(L²)</em> to <em>O​(L logL</em>). It is also important to leverage hardware (GPU) specifics.</p><p>Convolutional formulation allows for fast parallelized training. However, it is sometimes used at inference stage as well. The models that do it are sometimes referred to as <strong>long convolution sequence models (LCSMs)</strong>. Some papers even use primarily convolutional architectures with special kernels and windows (see, for example, <a href="https://arxiv.org/pdf/2302.10866.pdf">Hyena Hierarchy</a> or <a href="https://arxiv.org/pdf/2310.12109.pdf">Monarch Mixer</a>). In such cases, you may need to do additional work to use a pure-convolutional model in recurrent mode (see <a href="https://arxiv.org/pdf/2310.18780.pdf">Laughing Hyena Distillery</a>).</p><h4>2.4. Continuous-time recurrence: State space models</h4><p>State space models were initially created in 1960s to model continuous-time processes. A state space model is defined by the following ODE (ordinary differential equation):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXibPKx1l_h1DJ8TuHiS2A.png" /></figure><p>where <em>ẋ(t)</em> stands for the time derivative</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUzkbaSdTsrLZycmE9Lrfg.png" /></figure><p>Note that the role of <em>A</em> in this model differs a lot from the role of <em>A</em> in the recurrent model. However, if we choose a (small) step <em>T</em> and set</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3y_WP-F4FaZE3k0XZlZ0EQ.png" /></figure><p>we can make a <em>discretization</em> of (1) as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dd3MFuRgv_x9TPEbxxXKUA.png" /></figure><p>Here,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jd8W1W1r-sZw4ngi38jOVw.png" /></figure><p>However, working with matrix exponents is tough, so given that <em>T</em> is small, we can use various approximations for it. The simplest is <em>exp​(AT) ≈ I + AT</em>, which gives us approximations referred to as <em>Euler method</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sq2LgNDEh3kNB32GwwOWig.png" /></figure><p>so that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhYQIuVog2l-2cfK7I_jkQ.png" /></figure><p>However, <em>bilinear transform</em> is also widely used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vUerzsdL9ckR8BKAKL0ww.png" /></figure><p>Please keep in mind that even when AI engineers work with discretized versions, they often still parametrize SSMs with <em>A</em> and <em>B</em> from continuous-time formulation.</p><p><strong>An important remark about dimensions</strong>. All the formulas in this subsection are written for <strong>one-dimensional</strong> <em>uₜ</em> <strong>and one-dimensional</strong> <em>yₜ</em>. If <em>u</em> is <em>d</em>-dimensional, the same process occurs for every coordinate of <em>u</em>. This means, in particular, that a state space layer only performs time mixing (different coordinates of <em>uₜ</em> do not influence each other’s outputs) and relies on the MLP layer for channel mixing.</p><p><strong>Why does continuous formulation matter?</strong> There are several reasons:</p><ul><li>A continuous-time model can be discretized to various resolutions, allowing us to adapt it to different sampling frequencies without retraining.</li><li>Recent approaches make the discretization step data-dependant, thus creating an efficient feature selection technique. <a href="https://arxiv.org/pdf/2312.00752.pdf">Mamba</a> (see <a href="#112e">2.6</a>) is known to leverage this.</li></ul><h4>2.5. Architectures with Linear RNNs</h4><p>Linear RNNs take the place of an attention mechanism in the LM architectures. Here is an example, <a href="https://arxiv.org/pdf/2305.13048.pdf">RWKV</a> (Receptance Weighted Key Value, with the WKV block being recurrent-based):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*Mc8lj7gseAzdILHtXwCNIw.png" /><figcaption><a href="https://arxiv.org/pdf/2305.13048.pdf">Source</a></figcaption></figure><p>Here are several more, <a href="https://arxiv.org/pdf/2212.14052.pdf">H3</a> and <a href="https://arxiv.org/ftp/arxiv/papers/2312/2312.00752.pdf">Mamba</a> (SSMs are state space models):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgJJOaRfhUdT6AYvdFRFAA.png" /><figcaption><a href="https://arxiv.org/ftp/arxiv/papers/2312/2312.00752.pdf">Source</a></figcaption></figure><p>And, finally, <a href="https://arxiv.org/pdf/2402.19427.pdf">Hawk</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hg1MbZvRy0aAUqHZ-0Zmuw.png" /><figcaption><a href="https://arxiv.org/pdf/2402.19427.pdf">Source</a></figcaption></figure><p>Note that 1D convolutions also appear a way of establishing local connectivity in the time domain.</p><h4>2.6. Data-dependent gating</h4><p>Before 2017, when RNNs were still state-of-the-art in NLP, they used a complex gating mechanism to control memory flow. You can probably remember names such as LSTM and GRU. Recent RNN-based and state space models also use gating mechanisms.</p><p>It is interesting to note that MLP blocks are often gated as well. In RWKV, they even are recurrent.</p><p>Let’s check several examples of RNN gating:</p><p>— <a href="https://arxiv.org/abs/2305.13048"><strong>RWKV</strong></a> used a very sophisticated gating in its recurrent block, that can be summarized in the following scheme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPAzsuRo3dCQh9o3LX4wsA.png" /><figcaption><a href="https://arxiv.org/abs/2305.13048">Source</a></figcaption></figure><p>I am getting flashbacks about LSTM just from looking at it…</p><p>— <a href="https://arxiv.org/ftp/arxiv/papers/2312/2312.00752.pdf"><strong>Mamba</strong></a> makes the matrices <em>B</em> and <em>C</em> and the step size <em>T</em> in the state space model data-dependent.</p><p>If you want to see the formulas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFfepbW6YvuSgynB2ganUg.png" /></figure><p>Note that <em>T</em> is always positive, which is logical, because it is the discretization step.</p><p>Let’s see what it means by examining the Euler approximation for the discretization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8BlDDm9Pjf8zYuafC4n9A.png" /></figure><p>When <em>T</em> → 0, this preserves the state and ignores the current input, while for larger <em>T</em> the current input gets more focus.</p><p>Modifying <em>B</em> and <em>C</em> to be selective also allows for additional control over whether to let the information about the input <em>uₜ</em> into the state <em>xₜ</em> and whether to let the state into the output <em>yₜ</em>.</p><p>By the way, if you look at the code of Mamba, you will find out that it does the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aab7x-iKN9GjpLJV1pbyzA.png" /></figure><p>The authors of Mamba also leveraged hardware (GPU) capabilities to make their architecture more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3eXdBEVnzIUkPQcjJ-ArQ.png" /><figcaption><a href="https://arxiv.org/ftp/arxiv/papers/2312/2312.00752.pdf">Source</a></figcaption></figure><p>— <strong>Hawk</strong> (a subspecies of <a href="https://arxiv.org/pdf/2402.19427.pdf">Griffin</a>) suggests a Linear RNN model with the following recurrent layer architecture. Note that here we also have ⊙ (elementwise multiplication) instead of matrix multiplication:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*UIjuYtIdRe3aDqplGfImCA.png" /></figure><p>This mechanism, namely its</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRCJ_tRtGX55tk1MkXc91g.png" /></figure><p>coefficients, allows for flexible control of how much info is retained from the history (<em>xₜ</em>) and how much is introduced from the new input <em>uₜ</em>. The authors claim that it is more convenient than Mamba’s (exp​(<em>TA</em>), <em>TB</em>).</p><h4>2.7. Hybrid architectures</h4><p>Some authors note that using a mixture of recurrent blocks and multihead attention blocks improves quality while not undermining efficiency too much. Among interesting examples of hybrid architectures are the following:</p><ul><li><a href="https://huggingface.co/togethercomputer/StripedHyena-Hessian-7B">StripedHyena-Hessian-7B (SH 7B)</a> is a hybrid of attention and state space models (more accurately, gated convolutions arranged in Hyena operators, but it is not very important right now).</li><li><a href="https://arxiv.org/pdf/2402.19427.pdf">Griffin</a> is alternating between two Hawk (recurrent) blocks followed by one residual block with local multi-query attention.</li><li>Finally, <a href="https://arxiv.org/pdf/2403.19887.pdf">Jamba</a> combines the best things we have got in NLP now: Mamba layers, Transformer layers, and a Mixture-of-experts (16 experts in each MoE layer, 2 of them used at each token):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UoPvbBD6x37apmaWk2sanQ.jpeg" /><figcaption><a href="https://www.ai21.com/blog/announcing-jamba">Source</a></figcaption></figure><h4>2.8. Results and impact</h4><p><strong>2.8.1. Efficiency</strong></p><p>As you remember, we started with the problem of the inefficiency of transformers for long contexts. Inefficiency can come in the form of low inference latency or throughput. In this context, RNN-based models perform well. Let’s check it for our three best models: Mamba, Griffin, and Jamba.</p><p>Mamba paper reports that, in comparison to a similar-size Transformer model with FlashAttention-2:</p><ul><li>Mamba gets faster beyond 2K sequence length.</li><li>Mamba also achieves 4–5x higher inference throughput.</li></ul><p>Hawk and Griffin also keep a steady throughput with increasing context length while Multi-Query Attention-based transformer struggles with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ii_AXX5X9sAprNWVsmrEtw.png" /><figcaption><a href="https://arxiv.org/pdf/2402.19427.pdf">Source</a></figcaption></figure><p>Griffin looks worse than the pure Hawk due to its hybrid (Hawk + attention) structure, but it’s the price we have to pay for the quality.</p><p>As for Jamba, we’ll start with the memory comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18N2bOkWPt7-bhIhIW69gQ.jpeg" /><figcaption><a href="https://arxiv.org/pdf/2403.19887.pdf">Source</a></figcaption></figure><p>In terms of pure parameter count, Jamba is more or less on par with Mixtral (which also uses Mixture-of-experts). But Jamba only has attention layers now and then, so its kv-cache is relatively small. This allows Jamba to consume 2x the context length of Mixtral and 7x that of Llama-2-70B. For example, on 80GB NVIDIA A100 GPU, Jamba can work with 140K context length while Mixtral only with 64K.</p><p>In terms of throughput, with a context of 128K tokens, Jamba obtains 3x the throughput of Mixtral, while Llama-2-70B does not fit with such long context.</p><p><strong>2.8.2. Quality</strong></p><p>It wouldn’t be interesting to read about a fast but incapable model, so let’s discuss the quality of generation. The Griffin paper brings some promising hints like the benchmark performance…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAHiH7Sgc5L_oFukxlxeLQ.png" /><figcaption><a href="https://arxiv.org/pdf/2402.19427.pdf">Source</a></figcaption></figure><p>…or the ability to extrapolate to longer sequences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oS7I1ajlsZ0LO2qZpOxZ1w.png" /></figure><p>Jamba also shows good results on benchmarks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oW2Nw0T-C12Rd77Avuu5Ug.png" /><figcaption><a href="https://arxiv.org/pdf/2403.19887.pdf">Source</a></figcaption></figure><p>It also demonstrates good performance in the <a href="https://github.com/gkamradt/LLMTest_NeedleInAHaystack">needle-in-a-haystack evaluation</a> and performs on par with Mixtral on long QA benchmarks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5biw6Il1StlBcfj-rZ2viw.jpeg" /><figcaption><a href="https://arxiv.org/pdf/2403.19887.pdf">Source</a></figcaption></figure><p><strong>2.8.3. Beyond text</strong></p><p>At the beginning of 2024, there was much enthusiasm about Mamba, leading to several more Mamba-themed papers appearing. One example is <a href="https://arxiv.org/pdf/2401.09417.pdf">Vision Mamba</a>, whose authors created a Mamba-based model for working with images that scales well with increasing resolution (it is labeled as “Vim” on the plots).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQ3aOTyGWC8GDDuzNKV30w.png" /><figcaption><a href="https://arxiv.org/pdf/2402.19427.pdf">Source</a></figcaption></figure><p>We do not observe wide adoption of Linear RNN-based or state space models into production yet. Partially, I think, this is due to healthy human conservatism. But it may well change in the future.</p><p>I’ve initially prepared this material as part of the Practical Generative AI course by School of AI and Data Technologies. If you’re interested in studying LLMs and other generative models, their internal workings and applications, check out our <a href="http://ai-dt.school/generative-ai">program</a>. In the meantime, I’ll continue publishing very technical articles on the Nebius AI blog, so stay tuned.</p><h3>3. Paper reference</h3><h4>Relaxation of attention and Linear RNNs (non-state space models)</h4><ul><li><a href="https://arxiv.org/pdf/2105.14103.pdf">An Attention Free Transformer</a> — an attempt at relaxing quadratic complexity of a transformer.</li><li><a href="https://arxiv.org/pdf/2305.13048.pdf">RWKV</a> — block model with pure RNN time mixing blocks and recurrent MLP layers.</li><li><a href="https://arxiv.org/pdf/2303.06349.pdf">Resurrecting Recurrent Neural Networks for Long Sequences</a> — a very interesting theoretical analysis of Linear RNNs leading, in particular, to nice diagonal parametrization of <em>A</em>.</li><li><a href="https://arxiv.org/pdf/2402.19427.pdf">Griffin</a>.</li></ul><h4>State space models</h4><ul><li><a href="https://arxiv.org/pdf/2008.07669.pdf">HiPPO</a> — a new framework for understanding memory as compression capability.</li><li><a href="https://arxiv.org/pdf/2110.13985.pdf">Combining Recurrent, Convolutional, and Continuous-time Models with Linear State-Space</a> <a href="https://arxiv.org/pdf/2110.13985.pdf">Layers</a> — introduction of a Linear State-Space Layer (not for language modeling yet).</li><li><a href="https://arxiv.org/pdf/2111.00396.pdf">S4</a> (see also <a href="https://srush.github.io/annotated-s4/#part-1b-addressing-long-range-dependencies-with-hippo">this explanation</a>) — strives to further increase the efficiency of state space layers through wise use of linear algebra (considering normal + low rank matrices for <em>A</em>).</li><li><a href="https://arxiv.org/pdf/2212.14052.pdf">Hungry Hungry Hippos (H3)</a> — dared to apply SSMs to language modeling tasks. Used block architecture that you have seen in the subsection <a href="#d829">2.5</a>. Proposed the new FlashConv mechanism that further improved the traditional FFT + pointwise multiply + inverse FFT scheme.</li><li><a href="https://arxiv.org/pdf/2302.10866.pdf">Hyena Hierarchy</a> — a long convolution sequence model (LCSM), highly influenced by SSMs.</li><li><a href="https://www.together.ai/blog/stripedhyena-7b">StripedHyena-7B</a> — a model that leveraged all previous research (technically, it is a highly optimized hybrid of attention and gated convolutions arranged in Hyena operators).</li><li><a href="https://arxiv.org/ftp/arxiv/papers/2312/2312.00752.pdf">Mamba: Linear-Time Sequence Modeling with Selective State Spaces</a> — no introduction needed at this point, I think.</li><li><a href="https://arxiv.org/pdf/2403.19887.pdf">Jamba: A Hybrid Transformer-Mamba Language Model</a> — the recent hybrid of transformers, Mamba layers and MoE.</li><li>And finally, <a href="https://arxiv.org/pdf/2401.09417.pdf">Vision Mamba</a>.</li></ul><h3>3. Appendix</h3><h4>Continuous-time to discrete time</h4><p>This math-heavy topic was too heavy for a general overview, so I’ve put it here, for those curious.</p><p>Continuous-time formulation of a state space model is an ODE (ordinary differential equation):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ul7kpmwc86ETJhnQcFxbcQ.png" /></figure><p>where ẋ(t) stands for the time derivative</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUzkbaSdTsrLZycmE9Lrfg.png" /></figure><p>To discretize it, we choose a (small) step <em>T</em> and set <em>xₖ</em> = <em>x(kT)</em>. Now, we will infer from (2) something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BV_8-Tlcy6ui5Ht_ho00hw.png" /></figure><p>So, we need to integrate the first equation. Let’s multiply both sides by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UM5eUKgj_6A26fA4u1qLSw.png" /></figure><p>This is equivalent to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2GVwT4kf71zPiz76J0Xhg.png" /></figure><p>The left side is actually a derivative of a product, so we rewrite:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gz8_RzQQ8Q8ARiswCR7OVQ.png" /></figure><p>Now, we can integrate this using the fact that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9eyYyotF6D1PXqEMqhYfUg.png" /></figure><p>Let’s multiply both sides on</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFU_ndIN61LxwEWMWK-wWA.png" /></figure><p>Now, recall that we need to write a recurrence connecting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdcDLix4MYMk1x_sv_hjPA.png" /></figure><p>with <em>xₖ = x(kT). </em>Let’s write them both and see what can be done:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYwb3MoIPBTWaPJ73P4pbQ.png" /></figure><p>Now, we will need to assume that <em>u(t)</em> is constant during each timestep: that is, between each <em>kT</em> and <em>(k + 1)T</em>. That is a strong assumption, but, given that <em>T</em> is small, it is not devoid of some physical meaning. In this case, <em>Bu(τ)</em> under the second integral is a constant linear transformation <em>Bu(kT)</em> and it can be dragged away:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7DsIZwbnEau21tpyMS2pw.png" /></figure><p>Putting it all together, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vZ3Ejq5Wjnb6KuSCOconA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06cd3d91d42b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nebius/transformer-alternatives-in-2024-06cd3d91d42b">Transformer alternatives in 2024</a> was originally published in <a href="https://medium.com/nebius">Nebius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>