<?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 Jasleen Singh on Medium]]></title>
        <description><![CDATA[Stories by Jasleen Singh on Medium]]></description>
        <link>https://medium.com/@jasleen1991?source=rss-8c048e8abe71------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rP-96yaTC-pVUpU0</url>
            <title>Stories by Jasleen Singh on Medium</title>
            <link>https://medium.com/@jasleen1991?source=rss-8c048e8abe71------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:26:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jasleen1991/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[LLM Inference Optimization]]></title>
            <link>https://medium.com/@jasleen1991/llm-inference-optimization-15a8851aee70?source=rss-8c048e8abe71------2</link>
            <guid isPermaLink="false">https://medium.com/p/15a8851aee70</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[llm-inference]]></category>
            <dc:creator><![CDATA[Jasleen Singh]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 23:57:13 GMT</pubDate>
            <atom:updated>2025-02-21T00:33:12.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByBlEsR3aeIb25Q_1EMJ9w.png" /></figure><p>During the <strong>decode phase</strong>, the LLM generates tokens <strong>autoregressively</strong> until a stopping criterion is met. Each new token requires access to the <strong>keys and values</strong> from all previous tokens. This process is <strong>memory-bound</strong>, as transferring these weights to <strong>GPU memory</strong> often takes longer than the actual computation.</p><p>To optimize inference, the focus is on <strong>efficiently loading</strong> keys, values, activations, and weights into GPU memory. This improves <strong>GPU utilization</strong> and accelerates <strong>next-token generation</strong>, reducing latency.</p><h3>Prefill and decode phase of token generation</h3><p>Decoder-only models are trained using <strong>causal language modeling</strong>, where they predict the <strong>next word</strong> given a sequence of input tokens. They generate tokens <strong>autoregressively</strong> until a stopping criterion is met.</p><p>Token generation occurs in two phases:</p><p><strong>Prefill Phase:</strong></p><ul><li>The model processes the <strong>entire input sequence</strong> at once, computing <strong>intermediate states</strong> (keys and values) and generating the first token.</li><li>Since the full input is known, this involves <strong>matrix-matrix operations</strong>, which fully utilize the GPU, making it a <strong>compute-bound</strong> operation.</li></ul><p><strong>Decode Phase:</strong></p><ul><li>The model generates each <strong>subsequent token</strong> based on previously generated tokens.</li><li>This involves <strong>vector-matrix operations</strong>, which underutilize the GPU.</li><li>Here, latency is dominated by the time taken to <strong>load data</strong> (weights, activations, keys, values) into memory rather than computation, making it a <strong>memory-bound</strong> operation.</li></ul><p>Optimizing inference focuses on addressing the memory bottleneck to improve GPU utilization and accelerate token generation.</p><h3>Flash Attention</h3><p>Flash Attention is an optimized implementation of the <strong>attention mechanism</strong> in Transformer models, designed to <strong>reduce memory usage</strong> and <strong>accelerate computation</strong>. It achieves this by restructuring how the <strong>attention matrix</strong> is computed, eliminating the need to store large intermediate matrices found in standard implementations.</p><h4>Key Benefits:</h4><ul><li><strong>Efficient Memory Usage:</strong> Allows larger sequences and batch sizes to fit on the GPU without exceeding memory limits. Instead of storing the full attention matrix, <strong>FlashAttention processes it in a tiled (blocked) fashion</strong>, keeping only a small portion in memory at any given time.</li><li><strong>IO-Aware Optimization:</strong> Fuses multiple operations — <strong>matrix multiplication, softmax normalization, and weighted sum calculation</strong> — to minimize memory read/write operations, significantly improving speed.</li><li><strong>Exact Attention:</strong> Despite optimizing execution, <strong>FlashAttention preserves the original attention computation</strong>, ensuring accuracy is not compromised.</li></ul><p>By optimizing data flow and memory access patterns, FlashAttention <strong>enhances GPU efficiency</strong>, making Transformer models more scalable and performant.</p><h3>Batching</h3><p>This is the simplest method to improve GPU utilization. By batching multiple requests that use the same model, larger batches are transferred to GPU memory for concurrent processing, maximizing compute efficiency. However, the batch size can only be increased up to a limit before causing a memory overflow. Traditional batching is suboptimal because each request in the batch may generate a different number of completion tokens, leading to varying execution times. Consequently, all requests must wait for the longest one to complete, which can cause inefficiencies.</p><h3>In-Flight Batching</h3><p>This is the most straightforward approach to enhance GPU utilization. Multiple requests using the same model are batched together, and larger batches are transferred to GPU memory for concurrent processing, making better use of the available compute resources. However, the batch size can only be increased to a certain point before causing a memory overflow. Traditional batching is less efficient because each request in a batch may generate a different number of completion tokens, leading to varying execution times. As a result, all requests must wait for the longest-running one to finish, reducing overall throughput.</p><h3>Key-Value Caching</h3><p>A common optimization during the decode phase is KV caching. Since the decode process generates one token per time step, with each token depending on the key and value tensors of all previous tokens, recomputing these tensors at each step can be inefficient. To address this, KV caching stores these tensors in GPU memory. During each iteration, the newly computed elements are added to the running cache, making them available for the next iteration without the need for recomputation.</p><h3>Model Parallelism</h3><p><strong>Pipeline Parallelism: </strong>Pipeline parallelism involves splitting the model vertically into chunks, where each chunk consists of a subset of layers executed on separate devices. The output from one device is passed to the next, which processes the subsequent chunk.</p><p>The main limitation of this approach is that, due to the sequential nature of processing, some devices or layers may remain idle while waiting for the output (activations, gradients) from previous layers. This causes inefficiencies, or “pipeline bubbles,” in both the forward and backward passes.</p><p>Microbatching can help mitigate this by dividing the global batch size into smaller sub-batches, processed one at a time, with gradients accumulated at the end. This reduces the size of the pipeline bubbles but does not fully eliminate them.</p><p><strong>Tensor Parallelism:</strong> Tensor parallelism involves horizontally partitioning individual layers of the model into smaller, independent computation blocks that can be executed across different devices. Key components of transformers, such as attention blocks and multi-layer perceptron (MLP) layers, can benefit from tensor parallelism. In multi-head attention blocks, for example, each attention head — or group of heads — can be assigned to a different device, allowing them to be computed independently and in parallel.</p><p><strong>Sequence Parallelism: </strong>Sequence parallelism improves the processing of long sequences by distributing them across multiple GPUs. Rather than fitting the entire sequence on a single GPU, which may exceed memory limits, the sequence is divided into chunks, with each GPU handling a portion. The GPUs work in parallel, exchanging intermediate results to maintain coherence. This reduces memory bottlenecks and accelerates inference, particularly for large models dealing with lengthy text inputs. Sequence parallelism is often combined with techniques like tensor and pipeline parallelism to maximize efficiency and ensure smooth scaling during inference.</p><h3>Optimizing Attention Mechanism</h3><p>Multiple attention heads (MHA) are used to focus on different features, allowing the model to capture a richer understanding of the language by attending to various aspects simultaneously.</p><p><strong>Multi-Query Attention (MQA):</strong></p><p>In Multi-Query Attention (MQA), the keys and values are shared across multiple attention heads. While the computational workload in MQA is the same as Multi-Head Attention (MHA), the amount of data (keys, values) read from memory is significantly reduced. This is particularly beneficial when memory bandwidth is a limiting factor, as it improves compute utilization. Additionally, it reduces the size of the KV-cache in memory, allowing for larger batch sizes. However, this comes at the cost of reduced accuracy due to the sharing of keys and values among multiple heads.</p><p><strong>Grouped-Query Attention (GQA):</strong></p><p>Grouped-Query Attention (GQA) strikes a balance between Multi-Head Attention (MHA) and Multi-Query Attention (MQA) by grouping the keys and values into a few clusters of query heads. Within each group, it functions like MQA, sharing keys and values across the heads, while maintaining some of the flexibility of MHA.</p><h3>Paged KV Cache</h3><p>KV caches are sometimes “over-provisioned” to accommodate the largest possible input, as the size of inputs can be unpredictable. For instance, if a model supports a maximum sequence length of 2,048, memory is reserved for that size regardless of the actual input or output length, often resulting in unused space and memory fragmentation. This reserved memory remains allocated for the entire duration of the request.</p><p>Inspired by paging in operating systems, the Paged Attention algorithm addresses this by storing continuous keys and values in non-contiguous memory space. It partitions the KV cache for each request into blocks representing a fixed number of tokens, which are stored non-contiguously. These blocks are fetched as needed during attention computation, using a block table to track allocations. As new tokens are generated, additional blocks are allocated. The fixed block size eliminates inefficiencies caused by varying request sizes, significantly reducing memory waste and enabling larger batch sizes, which improves throughput.</p><h3>Dynamic Memory Compression</h3><p>Dynamic Memory Compression (DMC) involves compressing the KV cache during inference without sacrificing performance. For each token, attention head, and layer, the model decides whether the Key and Value pair should be appended to the existing KV cache or merged with the last one.</p><p>When appended, the KV cache size increases. However, when accumulated, the new pair is merged with the previous one using a weighted sum, reducing the cache size and saving memory. In a standard Transformer, the KV cache grows by one Key-Value pair (KVP) at a time. In contrast, with DMC, the model dynamically decides whether the next KVP should be merged with the last one in the cache.</p><p>This behavior is learned through a retrofitting process that trains a pre-existing LLM (e.g., Llama) with 2–8% of the training data:</p><ul><li>Initially, the model is trained to append each KVP to the cache.</li><li>Gradually, pressure is applied towards DMC, encouraging the model to average the new KVP with the previous one until the desired compression is achieved.</li><li>Once the target compression rate is reached, the process is fixed for the final retrofitting steps to consolidate the behavior.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15a8851aee70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generation AI Interview Questions — Transformers]]></title>
            <link>https://medium.com/@jasleen1991/generation-ai-interview-questions-transformers-0506ea403ba4?source=rss-8c048e8abe71------2</link>
            <guid isPermaLink="false">https://medium.com/p/0506ea403ba4</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Jasleen Singh]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 22:35:07 GMT</pubDate>
            <atom:updated>2025-02-20T22:47:11.324Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generation AI Interview Questions — Transformers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByBlEsR3aeIb25Q_1EMJ9w.png" /></figure><h3>What are Transformer Models and how do they work?</h3><p>Transformer models surpass RNNs by establishing relationships between a word and all other words in a sequence, regardless of their position. This is achieved through the <strong>attention mechanism</strong>.</p><h4>Encoder-Decoder Architecture:</h4><p>The transformer architecture consists of two main components: <strong>encoder</strong> and <strong>decoder</strong>, which work together and share similarities.</p><h4>Tokenization and Embeddings</h4><ul><li>Machine learning models process numbers, not words, so the first step is <strong>tokenization</strong>, where text is converted into numerical tokens.</li><li>Each token represents a word (or subword) and corresponds to an ID from the tokenizer’s vocabulary.</li><li>Tokens are then passed through an <strong>embedding layer</strong>, which transforms them into multi-dimensional vectors. These vectors capture the <strong>meaning</strong> and <strong>context</strong> of words in the input sequence.</li><li><strong>Positional encodings</strong> are added to preserve word order in the sequence.</li></ul><h4>Attention Mechanism</h4><ul><li>The sum of token embeddings and positional encodings is passed to the <strong>self-attention layer</strong>, which determines relationships between tokens.</li><li>The model learns self-attention weights during training, storing them in attention layers to reflect word relationships.</li><li><strong>Multi-head attention</strong> enables parallel learning, where each attention head captures different linguistic features.</li></ul><h4>Processing and Prediction</h4><ul><li>Once attention weights are applied, the data passes through a <strong>feed-forward network</strong>, outputting a vector of logits (raw scores for each token in the vocabulary).</li><li>These logits are then fed into a <strong>softmax layer</strong>, which normalizes them into probabilities.</li><li>The token with the highest probability is selected as the predicted word.</li></ul><p>This process allows transformers to generate highly contextualized responses, making them powerful for NLP tasks.</p><h3>Explain the Inference Process in Transformers.</h3><p><strong>Input Tokenization &amp; Encoding</strong></p><ul><li>In a task like translation, the input text is <strong>tokenized</strong> and passed through an <strong>embedding layer</strong>.</li><li>The embeddings are processed by <strong>multi-head attention layers</strong>, followed by a <strong>fully connected feed-forward layer</strong>, producing the <strong>encoder output</strong></li></ul><p><strong>Context Representation</strong></p><ul><li>The <strong>encoder output</strong> captures a deep representation of the <strong>meaning and context</strong> of the input sequence.</li></ul><p><strong>Decoding Process</strong></p><ul><li>The encoder output is passed to the <strong>decoder</strong>, influencing its <strong>self-attention layers</strong>.</li><li>A <strong>start-of-sequence token</strong> is fed into the decoder, prompting it to predict the next word based on the encoded context.</li></ul><p><strong>Generating Predictions</strong></p><ul><li>The decoder’s <strong>self-attention output</strong> is processed through a <strong>fully connected feed-forward layer</strong>.</li><li>The result is passed through a <strong>softmax layer</strong>, which generates probabilities for the next token.</li><li>The token with the highest probability is selected as the next word.</li></ul><p><strong>Iterative Generation &amp; Output</strong></p><ul><li>This process repeats, with each predicted token being fed back into the decoder until a <strong>stopping criterion</strong> (such as an end-of-sequence token) is met.</li><li>Finally, the predicted tokens are <strong>detokenized</strong> to generate the final output.</li></ul><h3>How is self-attention better than RNN?</h3><p>RNNs were used before transformers to predict the next word. To be able to successfully make a predict, just knowing the last word was not enough. It required knowing the whole sentence, sometimes entire document and also understanding of the language. The compute required to achieve was huge for a single sentence because of the sequential nature.</p><p>RNNs and LSTMs look at one word at a time, self-attention looks at all the words together, making the computation faster.</p><h3>Explain different types of positional encoding, absolute vs relative?</h3><p>Transformers do not process words sequentially like RNN or LSTM, they look at the entire sequence, so positional encoding is added to provide positional information of the words.</p><p><strong>Absolute Positional Encoding: </strong>In this method, each word is assigned a fixed encoding irrespective of the surrounding words. This positional encoding is added to the word to inform the model about the position. It is useful in summarization tasks where the relationship of the position is not important</p><p><strong>Relative Positional Encoding:</strong> Instead of assigning absolute positions, it encodes distance between the words allowing it to capture the contextual positioning of the words. It is useful where the order of the words change like in translation task.</p><h3>Explain beam search in decoding</h3><p>In beam search, during the decoding step, instead of predicting the token with the highest probability, it maintains multiple possible sequences and then decodes them step by step.</p><p>It starts with the start token and when the first token is predicted, instead of keeping just the token with the highest probability, it keeps k top tokens and then keeps of generating additional tokens, it calculates total probability at each step and keeps k sequences with total highest probability.</p><h3>What are some decoding strategies in Transformers?</h3><ul><li><strong>Greedy Decoding</strong> — Selects the word with the highest probability at each step, leading to deterministic but potentially suboptimal outputs.</li><li><strong>Top-k Sampling</strong> — Instead of always choosing the most probable word, it randomly samples from the <strong>top-k</strong> highest probability words, adding diversity.</li><li><strong>Top-p (Nucleus) Sampling</strong> — Selects from a <strong>dynamically determined subset</strong> of words whose cumulative probability exceeds a threshold ppp, ensuring more flexible yet controlled randomness.</li><li><strong>Temperature Scaling</strong> — Adjusts the softmax probability distribution; <strong>lower values (e.g., 0.2)</strong> make predictions more deterministic, while <strong>higher values (e.g., 1.5)</strong> increase randomness.</li></ul><h3>What is Self-Attention?</h3><p>Self-attention, a key component of the Transformer architecture, has revolutionized the field of natural language processing due to its effectiveness in modeling complex patterns in sequences. Here’s a breakdown of self-attention:</p><h4>Overview:</h4><p>Self-attention allows a sequence (e.g., a sentence) to focus on different parts of itself to produce a representation of the sequence. In essence, it lets the model weigh the importance of different words or tokens in relation to a specific word.</p><h4><strong>Mechanism:</strong></h4><p>Given an input sequence, the self-attention mechanism calculates attention scores for every word against every other word in the sequence. These scores determine how much focus each word in the sequence should have on every other word.</p><h4>Query, Key, Value Vectors:</h4><p>For each word/token, we derive three vectors:</p><ol><li>Query vector: Represents the word we’re focusing on.</li><li>Key vector: Represents the words we’re comparing against.</li><li>Value vector: Provides the information from each word which we’ll use in our final output.</li></ol><p>These vectors are derived by multiplying the embedding of each word with three weight matrices (which are learned during training).</p><p><strong>Attention Score Calculation: </strong>For a given word’s Query vector, we calculate its dot product with the Key vector of every other word. This gives us the attention scores.</p><p><strong>Softmax:</strong> The attention scores are then passed through a softmax function, which converts them to probabilities. This ensures that the scores are normalized and sum up to 1.</p><p><strong>Weighted Sum:</strong> The softmax scores for each word are multiplied with their respective Value vectors. The results are summed up to produce the final self-attended representation of the word.</p><p><strong>Multi-Head Attention:</strong> Instead of doing this process once, the Transformer architecture does it multiple times in parallel, with each set using different weight matrices. This allows the Attention weights to learn different features of the input.</p><h3>What are word/token embeddings and how are they trained?</h3><p><strong>Word/Token Embeddings</strong> are numerical representations of words (or tokens) that capture their semantic meaning, allowing machine learning models to work with textual data effectively. In traditional machine learning, models struggle with raw text because computers can’t understand text directly. <strong>Word embeddings</strong> transform words into <strong>dense vectors</strong>, where each word is represented as a point in a high-dimensional space. The distance between these points reflects the <strong>semantic similarity</strong> between words.</p><h3>Explain skip gram for word embeddings. Specifically, how to construct positive and negative samples?</h3><p>The <strong>Skip-Gram</strong> model is one of the two architectures used in <strong>Word2Vec</strong> (the other being Continuous Bag of Words or <strong>CBOW</strong>). The goal of the Skip-Gram model is to predict the <strong>context</strong> words (surrounding words) given a <strong>target word</strong>. The Skip-Gram model works by using a target word in the center of a context window and attempts to predict the words around it.</p><p>For example, given a sentence:<br> <strong>“The cat sat on the mat.”</strong></p><p>If we use a context window of size 2 (i.e., 2 words to the left and 2 words to the right), and the target word is <strong>“sat”</strong>, then the model would try to predict the context words <strong>[“the”, “cat”, “on”, “the”]</strong> given <strong>“sat”</strong>.</p><p><strong>Constructing Positive and Negative Samples in Skip-Gram</strong></p><p>In order to train the model, we need to define positive and negative samples:</p><p><strong>Positive Samples:</strong></p><ul><li>Positive samples represent the <strong>true context</strong> of a word. They are <strong>pairs of target and context words</strong> that actually appear in the training data.</li><li>For example, in the sentence “The cat sat on the mat”, the word “sat” might be the target word, and its <strong>positive context words</strong> (for a window size of 2) would be <strong>[“the”, “cat”, “on”, “the”]</strong>.</li><li>Each of these pairs is a <strong>positive sample</strong>.</li></ul><p><strong>Positive sample construction:</strong></p><ul><li>For each word in the sentence, the model selects the <strong>target word</strong> (center word) and pairs it with all the <strong>context words</strong> (those within the window size).</li><li>Example (for window size = 2):</li><li><strong>Target word</strong>: “sat”</li><li><strong>Context words</strong>: “the”, “cat”, “on”, “the”</li><li>Positive samples: <strong>(“sat”, “the”)</strong>, <strong>(“sat”, “cat”)</strong>, <strong>(“sat”, “on”)</strong>, <strong>(“sat”, “the”)</strong></li></ul><p><strong>Negative Samples:</strong></p><ul><li>Negative samples are <strong>pairs of words</strong> that are not contextually related. They are randomly selected pairs of words where the target and context do not actually appear together in the same context window.</li><li>The purpose of negative sampling is to <strong>contrast</strong> the positive samples. In other words, the model learns to differentiate between real context words (positive samples) and random, irrelevant words (negative samples).</li></ul><p><strong>Negative sample construction:</strong></p><ul><li>Randomly select <strong>words from the vocabulary</strong> that are <strong>not</strong> in the context of the target word.</li><li>The number of negative samples is typically <strong>much larger</strong> than the number of positive samples (often 5–20 negative samples for each positive sample).</li><li>For example, if “sat” is the target word and its context words are “the”, “cat”, “on”, “the”, negative samples might be random words like <strong>“dog”</strong>, <strong>“walk”</strong>, <strong>“green”</strong>, <strong>“bicycle”</strong>, etc.</li></ul><h3>What is the maximum input length of BERT? Why do we need to use such restrictions for downstream tasks?</h3><p>The <strong>maximum input length</strong> for BERT is <strong>512 tokens</strong>. This means that when using BERT, the input sequence cannot exceed 512 tokens. If the input sequence exceeds 512 tokens, it needs to be truncated, and if it’s shorter, it is typically padded to the same length.</p><p>There are several reasons why BERT and similar transformer-based models impose this restriction on input length:</p><ol><li><strong>Computational Complexity</strong></li></ol><p>Transformers, including BERT, rely on <strong>self-attention</strong> mechanisms, where each token attends to every other token in the sequence. The <strong>self-attention matrix</strong> grows quadratically with respect to the input length:</p><ul><li>The memory and computational complexity of the self-attention mechanism is <strong>O(n²)</strong></li></ul><p>This quadratic growth in complexity makes it infeasible to use very long sequences in terms of both <strong>memory</strong> and <strong>computation</strong>.</p><p><strong>2. Memory Constraints</strong></p><p>The self-attention mechanism also requires storing intermediate results for each pair of tokens in the sequence, leading to high memory usage. If the input length were much longer, it would require excessive memory for storing these pairwise attention weights. To fit within hardware limitations (such as <strong>GPU memory</strong>), the maximum input length is restricted to 512 tokens.</p><p><strong>3. Model Training and Performance</strong></p><p>BERT was originally trained on a fixed-length input of 512 tokens. Extending the sequence length during inference would require retraining or fine-tuning the model to handle longer sequences. The model’s architecture (number of layers, attention heads, etc.) was designed with this constraint in mind.</p><p><strong>4. Positional Embeddings</strong></p><p>In BERT, the position of each token is encoded using <strong>positional embeddings</strong>, which are vectors added to the token embeddings to provide information about the token’s position in the sequence. These embeddings are designed to handle a fixed maximum sequence length (512). Extending the sequence length would require expanding these positional embeddings, which could lead to inconsistencies with the model’s pre-trained embeddings.</p><p><strong>Why Do We Need the Restriction for Downstream Tasks?</strong></p><p>The restriction on input length is particularly relevant for <strong>downstream tasks</strong> like text classification, question answering, named entity recognition, etc. due to memory efficiency. For tasks like question answering, if the input text is too long (e.g., a full-length article), it would exceed the model’s input limit. Therefore, the input must be truncated to fit within the 512-token constraint, which can cause parts of the text to be ignored.</p><h3>What is Attention with Linear Biases (ALiBi)?</h3><p>ALiBi is a simple yet effective way to help transformers understand the order of words in a sentence <strong>without</strong> using traditional position embeddings.</p><ol><li><strong>No extra Positional Embeddings</strong>: Most transformers add position embeddings to word embeddings to indicate the order of words. ALiBi skips this step and instead modifies attention scores directly.</li><li><strong>Adding a Distance-Based Penalty: </strong>In self-attention, each word compares itself to all other words in the sequence. ALiBi penalizes words that are farther apart by subtracting a small bias from their attention scores. The farther two words are, the larger the penalty, making the model pay more attention to closer words.</li></ol><p><strong>Why is this useful?</strong></p><ol><li><strong>More Efficient: </strong>No need to store large position embedding tables.</li><li><strong>Generalizes to Longer Sequences: </strong>Since it applies a simple rule instead of fixed embeddings, it works well even for sequences longer than the ones seen during training.</li><li><strong>Improves Attention Focus: </strong>Helps the model focus more on nearby words, which is often useful for understanding language.</li></ol><p><strong>Think of it like this:</strong> Imagine you are listening to a conversation. You remember words that were spoken just a moment ago better than those from a long time ago. ALiBi makes transformers do something similar — prioritizing nearby words while still considering distant ones with a small penalty.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0506ea403ba4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>