<?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 Pranay Janupalli on Medium]]></title>
        <description><![CDATA[Stories by Pranay Janupalli on Medium]]></description>
        <link>https://medium.com/@pranay.janupalli?source=rss-ff450d4f6179------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4-5gRucow9d49etj.jpg</url>
            <title>Stories by Pranay Janupalli on Medium</title>
            <link>https://medium.com/@pranay.janupalli?source=rss-ff450d4f6179------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:13:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pranay.janupalli/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[Introduction to NCCL Communication Operators: The Backbone of Efficient Distributed Training]]></title>
            <link>https://medium.com/@pranay.janupalli/introduction-to-nccl-communication-operators-the-backbone-of-efficient-distributed-training-d8b4b2f990a6?source=rss-ff450d4f6179------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8b4b2f990a6</guid>
            <category><![CDATA[nccl]]></category>
            <category><![CDATA[data-parallelism]]></category>
            <category><![CDATA[model-sharding]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[Pranay Janupalli]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 13:34:29 GMT</pubDate>
            <atom:updated>2024-07-12T13:34:29.945Z</atom:updated>
            <content:encoded><![CDATA[<p>In the rapidly evolving landscape of deep learning, achieving efficient and scalable training across multiple GPUs is paramount. Whether you’re working with Fully Sharded Data Parallel (FSDP) or Distributed Data Parallel (DDP), the performance of your distributed training setup hinges on the communication between GPUs. This is where NCCL (NVIDIA Collective Communication Library) communication operators come into play.</p><p>NCCL provides a highly optimized, multi-GPU collective communication library that enables seamless data exchange across GPUs, ensuring that the data movement overhead is minimized and the training process is accelerated. By leveraging NCCL’s capabilities, developers can unlock the full potential of their hardware, leading to faster training times and more efficient use of resources.</p><p>In this blog, we will delve into the core NCCL communication operators, explore their significance in distributed training, and illustrate how they form the backbone of DDP and FSDP. Whether you are a seasoned researcher or a newcomer to the field, understanding these operators will provide you with the tools to optimize your deep learning models and push the boundaries of what’s possible.</p><h3><strong>NCCL Collective Communication Operations</strong></h3><ol><li><strong>Broadcast:</strong><br>- The Broadcast operation in NCCL copies data from one GPU (the root rank) to all other participating GPUs.<br>- Specifically, One GPU is designated as the root rank, which holds the data to be broadcast. he data from the root rank is then copied to all other participating GPUs. Thereby, the data is replicated identically on all GPUs after the operation.</li><li><strong>Reduce:</strong><br>- The Reduce operation performs a reduction operation (e.g. sum, max, min, avg) across all participating GPUs and stores the result only on the specified root GPU.<br>- This is useful when you only need the final reduced result on a single GPU, rather than having the result replicated on all GPUs.<br>- For example, in distributed training, the gradients computed on each GPU can be reduced to the root GPU using <strong>Reduce</strong>, and then the updated model parameters can be broadcast back to all GPUs using <strong>Broadcast</strong>.</li><li><strong>AllReduce:</strong><br>- The AllReduce operation also performs a reduction operation across all participating GPUs, but stores the final result on every GPU.<br>- <strong>This is a very common operation in distributed training, as it allows each GPU to have the fully aggregated results (e.g. summed gradients) without requiring an additional broadcast step.</strong><br>- AllReduce is efficient because it can be implemented using a ring-based algorithm that minimizes data movement.</li><li><strong>ReduceScatter:</strong><br>- ReduceScatter first performs a reduction operation like Reduce, but then scatters the result in equal-sized blocks across the participating GPUs.<br>- This can be more efficient than AllReduce when you only need a portion of the final result on each GPU, rather than the full aggregated result.<br>- <strong>This is used in FSDP gradient scattering after performing all gather backward pass.</strong><br>- ReduceScatter followed by AllGather is equivalent to an AllReduce operation.</li><li><strong>AllGather:</strong><br>- The AllGather operation gathers data from all participating ranks (GPUs) and distributes the concatenated result evenly to all ranks.<br>- Specifically, Each rank contributes a contiguous block of data of equal size. These blocks are concatenated in rank order to form the final result. The final result is then scattered back to all ranks.<br>- <strong>So if each rank contributes a block of size N, the final result on each rank will be a buffer of size K*N, where K is the total number of ranks.</strong><br>- The AllGather operation is useful when you need to collect data from all ranks into a single buffer on each rank. For example, Gathering model parameters or optimizer states across GPUs in distributed training.<br>- <strong>It is used in FSDP to collect FSDP unit parameters for forward pass and backward pass.</strong><br>- The main benefit of AllGather is that it allows you to <strong>efficiently collect data from all ranks onto each rank, without requiring a separate gather step on a root rank</strong>. The data is evenly distributed to all ranks in a single collective call.</li></ol><h3>Conclusion:</h3><p>Understanding and utilizing NCCL communication operators is crucial for optimizing distributed training in deep learning. By effectively employing Broadcast, Reduce, AllReduce, ReduceScatter, and AllGather, FSDP and DDP enhance the performance. These operators help streamline data exchange between GPUs, reducing overhead and speeding up the training process. Understanding these operators allows you to make the most of your hardware, leading to faster and more efficient model training. As deep learning continues to evolve, leveraging NCCL communication operators will be essential for achieving scalable and efficient training solutions.</p><h3>Resources:</h3><p><a href="https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/operations.html">https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/operations.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8b4b2f990a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Model Sharding and Model Parallelism: Scaling Large Language Models]]></title>
            <link>https://medium.com/@pranay.janupalli/understanding-model-sharding-and-model-parallelism-scaling-large-language-models-dee6144d0591?source=rss-ff450d4f6179------2</link>
            <guid isPermaLink="false">https://medium.com/p/dee6144d0591</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[model-parallelism]]></category>
            <category><![CDATA[model-sharding]]></category>
            <dc:creator><![CDATA[Pranay Janupalli]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 16:10:41 GMT</pubDate>
            <atom:updated>2024-07-07T16:10:41.274Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of large-scale models, particularly large language models (LLMs), managing memory and computational resources efficiently is a significant challenge. Two techniques often used to tackle this challenge are <strong>model sharding</strong> and <strong>model parallelism</strong>. While these concepts are related, they have distinct differences and use cases. In this blog post, we will explore what model sharding and model parallelism are, how they work, how they differ, and the practical applications of these techniques.</p><p><strong>What is Model Sharding?</strong><br>Model sharding involves dividing a large model into smaller, more manageable pieces or “shards” and distributing these shards across multiple devices or machines. This technique is particularly useful for models that are too large to fit into the memory of a single device.</p><p><strong>How Model Sharding Works</strong><br><strong><em>1. Splitting the Model:</em></strong><br> The model is divided into smaller parts. For instance, a 32-layer model might be split into two shards: the first 16 layers in one shard and the remaining 16 layers in another.<br><br><strong><em>2. Distributing the Shards:</em></strong><br>These shards are assigned to different GPUs or machines. Each device handles its respective shard during computation.</p><p><strong><em>3. Parallel Processing:</em></strong><br>During inference or training, each device processes its shard of the model. The results are then aggregated to produce the final output.</p><p><strong>Example of Model Sharding<br></strong>Consider a 9-billion-parameter language model with 32 layers, split into two shards:<br><strong><em>- Shard 1: Contains the first 16 layers.</em></strong><br><strong><em>- Shard 2: Contains the last 16 layers.</em></strong></p><p>In this setup, Shard 1 is processed on GPU 1, and Shard 2 is processed on GPU 2. During inference, the input data is fed into GPU 1, processed through the first 16 layers, then the intermediate result is passed to GPU 2, which processes it through the remaining layers to produce the final output. During batch inference with multiple device, using pipelining inference speed improves.</p><p><strong>Model Sharding with Offloading</strong><br>What if you have a single GPU with limited memory? Model sharding can still be useful by offloading weights between the CPU and GPU. Here’s how this can work:</p><p><strong>Scenario Breakdown</strong><br>Shards:<br> — Shard 1: 12 GB<br> — Shard 2: 8 GB<br>Hardware:<br> — GPU: 16 GB memory<br> — CPU: Sufficient RAM to hold the model weights not currently on the GPU<strong><br>Offloading Process</strong><br><strong><em>1. Initial Setup:</em></strong><br> — Both shards of the model are initially stored in the CPU RAM because the combined size (20 GB) exceeds the GPU memory capacity (16 GB).<br><strong><em>2. Forward Pass (Inference) or Training:</em></strong><br><strong>Step 1:</strong> <br> — Load Shard 1 (12 GB) onto the GPU.<br> — Process the input data through the layers of Shard 1.<br> — Store intermediate results in GPU memory or transfer them to CPU RAM if GPU memory is limited.<br><strong>Step 2: </strong><br> — Unload Shard 1 from the GPU and transfer it back to CPU RAM.<br> — This step frees up the GPU memory for the next shard.<br><strong>Step 3:</strong> <br> — Load Shard 2 (8 GB) onto the GPU.<br> — Process the intermediate results from Shard 1 through the layers of Shard2.<br> — Generate the final output or further intermediate results if needed.</p><p><strong>What is Model Parallelism?</strong><br><em>Model parallelism is a broader term that encompasses various strategies for distributing parts of a model across multiple devices to perform computations in parallel. Model sharding is a form of model parallelism, but not all model parallelism techniques involve sharding.</em></p><p><strong>Few Types of Model Parallelism</strong><br>1. Intra-layer Parallelism (Tensor Parallelism):<br><em> — Splits the computation within a single layer across multiple devices. For example, a large matrix multiplication operation can be divided among multiple GPUs.</em><br>2. Inter-layer Parallelism (Pipeline Parallelism):<br> <em>— Splits different layers of the model across multiple devices. For instance, assigning the first half of the layers to one GPU and the second half to another.</em></p><p><strong>Differences Between Model Sharding and Model Parallelism</strong><br>- <strong>Granularity:</strong><br> — <em>Model Sharding:</em> Focuses on dividing the model into large chunks or shards, typically at the layer level.<br> — <em>Model Parallelism:</em> Can involve both coarse-grained (layers) and fine-grained (within-layer operations) distribution of computations.<br>- <strong>Implementation:</strong><br> — <em>Model Sharding:</em> Usually involves a straightforward split of the model’s layers or sections across devices.<br> — <em>Model Parallelism:</em> Can involve more complex strategies, such as splitting within layers or coordinating different types of operations across devices.<br>- <strong>Use Cases:</strong><br> — <em>Model Sharding:</em> Commonly used for very large models that cannot fit into the memory of a single device.<br> — <em>Model Parallelism:</em> Used to improve computational efficiency and performance, whether for large or smaller models.</p><p><strong>When to Use Different Sharding Methods</strong><br>- <strong>Model Sharding Across Multiple GPUs:</strong><br> — <em>Use Case:</em> When you have multiple GPUs available and the model size exceeds the memory capacity of a single GPU.<br> — <em>Advantage:</em> Enables parallel processing of model layers, leading to faster computation.<br> — <em>Disadvantage:</em> Requires multiple GPUs and careful synchronization.<br>- <strong>Model Sharding with Offloading (Single GPU):</strong><br> — <em>Use Case:</em> When you have only one GPU with limited memory but sufficient CPU RAM.<br> — <em>Advantage:</em> Allows large models to be processed on a single GPU by dynamically offloading weights.<br> — <em>Disadvantage:</em> May introduce latency due to data transfer between CPU and GPU.</p><p><strong>Advantages of Model Sharding</strong><br><em>1. Scalability:</em> Enables the use of larger models by distributing memory and computational requirements.<br><em>2. Efficiency:</em> Makes efficient use of available hardware resources.<br><em>3. Flexibility:</em> Can be adapted to different hardware setups and scales.<br><em>4. Improved Inference Speed:</em> In a multi-GPU setup, different shards can be processed in parallel, reducing inference time compared to sequential processing.</p><p><strong>Disadvantages of Model Sharding</strong><br><em>1. Complexity:</em> Adds complexity to model deployment and management.<br><em>2. Synchronization:</em> Requires careful synchronization to ensure consistency and correctness.<br><em>3. Communication Overhead:</em> Data transfer between devices can introduce latency and require high communication bandwidth.<br><em>4. Fault Tolerance:</em> Implementing fault tolerance mechanisms adds additional complexity.</p><p><strong>Conclusion</strong><br>Model sharding and model parallelism are essential techniques for scaling large language models and other complex machine learning models. While model sharding specifically involves splitting the model into shards and distributing them across devices, model parallelism includes a variety of strategies for parallelizing computations at different levels of granularity. Understanding these techniques and their differences is crucial for effectively managing the memory and computational demands of large-scale models.<br>By leveraging model sharding and model parallelism, we can push the boundaries of what’s possible with machine learning, enabling the development of even more powerful and sophisticated models. Whether using multiple GPUs or a single GPU with offloading, these techniques ensure efficient and scalable model processing.</p><p>REFERENCES:<br><a href="https://huggingface.co/blog/accelerate-large-models">https://huggingface.co/blog/accelerate-large-models</a><br><a href="https://huggingface.co/docs/accelerate/concept_guides/big_model_inference">https://huggingface.co/docs/accelerate/concept_guides/big_model_inference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dee6144d0591" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethical NLP: A Pseudonymization Approach to Privacy and Bias Mitigation]]></title>
            <link>https://medium.com/@pranay.janupalli/ethical-nlp-a-pseudonymization-approach-to-privacy-and-bias-mitigation-d4271929d226?source=rss-ff450d4f6179------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4271929d226</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[responsible-ai]]></category>
            <category><![CDATA[nlp-training]]></category>
            <category><![CDATA[data-anonymization]]></category>
            <category><![CDATA[ethical-ai]]></category>
            <dc:creator><![CDATA[Pranay Janupalli]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 18:18:07 GMT</pubDate>
            <atom:updated>2024-04-18T18:18:07.642Z</atom:updated>
            <content:encoded><![CDATA[<p>In the rapidly evolving field of Natural Language Processing (NLP), the development of robust text generation and classification models is a continuous pursuit. However, this pursuit is not without its ethical challenges, particularly when dealing with sensitive client data or personal information. The ethical concerns surrounding privacy and bias are significant, as models trained on such data can unintentionally perpetuate or even amplify existing societal biases. In this professional blog post, we delve into the complexities of training NLP models with sensitive information and propose a simple yet effective solution: pseudonymization.</p><h3>Navigating the Ethical Landscape</h3><p>Training NLP models with sensitive data presents several challenges:<br>1.<strong>Privacy Concerns:</strong> Traditional approaches to model training often involve the direct utilization of raw data, posing significant risks of data breaches or unintentional exposure.<br><strong>2.Bias Amplification</strong>: Text classification models, if not carefully trained, can exhibit bias towards certain attributes such as gender, race, or socioeconomic status present in the data. This bias, when ingrained in the model, can lead to discriminatory outcomes in downstream applications.<br><strong>3.Generation of Sensitive Information:</strong> Text generation models, trained on sensitive data, run the risk of generating output that inadvertently discloses confidential information. This can pose legal and ethical challenges, especially in regulated industries like healthcare or finance.</p><h3>Pseudonymization: A Robust Solution for Privacy and Bias Mitigation</h3><p>Pseudonymization offers a compelling solution to these ethical quandaries. By replacing identifiable information with pseudonyms or synthetic data, privacy risks are significantly reduced without compromising the utility of the data for model training. Let’s explore how pseudonymization addresses the aforementioned challenges:<br><strong>1.Privacy Preservation:</strong> Pseudonymization ensures that sensitive information such as names, addresses, or other personally identifiable details are replaced with anonymized identifiers. This minimizes the risk of identifying individuals, even if the data is accessed by unauthorized parties.<br><strong>2.Bias Mitigation:</strong> By anonymizing sensitive attributes within the data, pseudonymization helps mitigate the risk of bias amplification during model training. Attributes such as gender or ethnicity can be pseudonymized, ensuring that the model learns to generalize without perpetuating societal biases.<br><strong>3.Confidentiality in Text Generation:</strong> In the context of text generation, pseudonymization enables the creation of synthetic data that retains the statistical properties of the original corpus while safeguarding sensitive information. This ensures that generated text does not inadvertently disclose confidential details present in the training data.</p><p><strong>Integrating Pseudonymization into the Data Preprocessing Pipeline</strong><br>To effectively leverage the benefits of pseudonymization, it’s essential to integrate it into the data preprocessing pipeline.<br><strong>When to Use Pseudonymization in the Preprocessing Pipeline</strong><br>Pseudonymization is particularly useful in projects where the entities within the data hold minimal significance to the analysis or model training process. Here’s why:<br><strong>1.Privacy Preservation:</strong> Pseudonymization safeguards the privacy of individuals without compromising the integrity of the data.<br><strong>2.Bias Mitigation:</strong> By anonymizing attributes with minimal relevance to the analysis, pseudonymization promotes fairness and impartiality in the model’s predictions.<br><strong>3.Synthetic Data Generation:</strong> Pseudonymization facilitates the creation of privacy-compliant synthetic datasets for tasks like data augmentation or text generation, ensuring confidentiality while preserving statistical properties.<br><strong>When Not to Use Pseudonymization in the Preprocessing Pipeline</strong><br>However, caution should be exercised when considering pseudonymization in projects where the factual accuracy of individual data points is paramount. Here are some scenarios where pseudonymization may not be the best choice:<br><strong>1.Data Integrity Concerns:</strong> In projects where preserving the factual accuracy and granularity of individual data points is essential, pseudonymization may result in a loss of data utility or analytical depth.<br><strong>2.Contextual Understanding:</strong> In projects where contextual understanding of individual entities or attributes is critical to the analysis or model outcomes, pseudonymization may obscure crucial insights.</p><h3>Embracing Ethical AI Development</h3><p>In the pursuit of advancing NLP technology, it is imperative to prioritize ethics and responsible data practices. Pseudonymization emerges as a powerful tool for addressing privacy concerns and mitigating bias in NLP model training. By integrating pseudonymization into the data preparation stage, NLP engineers can uphold privacy principles and foster fairness and equity in AI applications. As we navigate the complex landscape of data-driven innovation, let us embrace pseudonymization as a fundamental part of ethical AI development.</p><h3><strong>References:</strong></h3><ol><li><a href="https://arxiv.org/pdf/2306.05561.pdf">https://arxiv.org/pdf/2306.05561.pdf</a></li><li><a href="https://huggingface.co/grammarly/pseudonymization-seq2seq">https://huggingface.co/grammarly/pseudonymization-seq2seq</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4271929d226" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain-Specific Embedding Models: A Journey of Adaptation and Fine-Tuning]]></title>
            <link>https://medium.com/@pranay.janupalli/domain-specific-embedding-models-a-journey-of-adaptation-and-fine-tuning-b2b51f037d17?source=rss-ff450d4f6179------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2b51f037d17</guid>
            <category><![CDATA[domain-adaptation]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[domain-adaption]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <category><![CDATA[embedding-model]]></category>
            <dc:creator><![CDATA[Pranay Janupalli]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 17:30:08 GMT</pubDate>
            <atom:updated>2024-04-18T17:30:08.568Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever tried building a search engine tailored to a specific domain, only to find the results lacking the finesse you expected? Perhaps you observed mediocre performance or outright disappointment in the relevance of search results. If this sounds familiar, you’re not alone. The culprit? Your embedding model might be missing out on the nuances of your domain.</p><p>In this blog, we’re diving deep into domain-specific embedding models. We’ll explore how you can train your very own embedding model to understand the nuances of your domain, unlocking its true potential.</p><h4>The Need of Domain Adaption:</h4><p>Imagine building a search engine for medical research articles without understanding medical terminology or context. It’s like navigating through a dense forest blindfolded. This lack of domain-specific knowledge cripples the effectiveness of embedding models in capturing the essence of your data.</p><h4>Domain Adaption of Embedding Model</h4><p>Domain Adaption of an Embedding model can be done in two stages. <br>1. Adaptive Pretraining<br>2. Task specific finetuning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*beaBzaPT43pDltczFRMNKQ.png" /><figcaption>workflow of domain finetuning of embeddings</figcaption></figure><h4>Prepare Base Embedding</h4><p>Let’s delve into the process of preparing the base embedding model of your choice, setting the stage for subsequent domain-specific refinements. The base embedding model is constructed by integrating a pooling layer with a pre-trained language model, tailored to suit your specific requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*eQg7OpQ0DjWh7NFiWIIXEA.png" /></figure><p><strong>Pooling Layer Integration:</strong><br>The crux of base embedding preparation lies in the integration of a pooling layer with the language model. This pivotal step enables the aggregation of contextualized representations generated by the language model into fixed-dimensional embeddings. Depending on your desired embedding dimensionality, the configuration of the pooling layer varies.<br>Here are few pooling techniques:</p><p><strong>1. Mean Pooling:</strong><br>This technique computes the mean of all contextualized token representations, yielding a consolidated embedding that captures the average semantic essence of the input text. Mean pooling offers simplicity and computational efficiency, making it a popular choice in various applications.</p><p><strong>2. [CLS] Token Pooling:</strong><br>The [CLS] token, a special token introduced by models like BERT, encapsulates the overall contextual representation of the input sequence. [CLS] token pooling involves solely utilizing the representation of the [CLS] token as the embedding output. This approach is particularly suited for tasks requiring a single, holistic representation of the input sequence.</p><p><strong>3. Weighted Mean Pooling:</strong><br>In contrast to mean pooling, weighted mean pooling assigns different weights to individual token representations based on their significance. This enables the model to prioritize salient tokens, thereby enhancing the discriminative power of the resulting embeddings. Weighted mean pooling is particularly advantageous in scenarios where certain tokens carry more semantic weight than others.</p><p><strong>4. Max Pooling:</strong><br>Max pooling computes the maximum value across each dimension of the token representations, capturing the most salient features within the input sequence. This technique emphasizes the presence of critical information, making it well-suited for tasks requiring robust feature extraction.</p><p>Now getting to domain finetuning:<br><strong>1. Adaptive Pretraining of Base Embedding:</strong><br>Adaptive Pretraining constitutes the base of our domain adaptation. Herein, the model undertakes an unsupervised immersion in domain-specific corpora, employing techniques to draw the underlying semantic and syntactic structures inherent to the domain.<br>There are many techniques for adaptive pretraining of embeddings. Here are few:<br><strong> i. Masked Language Modelling <br>ii. Contrastive Tension<br>iii. SimCSE: Simple Contrastive Learning of Sentence Embeddings<br>iv. BERT-flow<br>v. TSDAE: Using Transformer-based Sequential Denoising Auto-Encoder for Unsupervised Sentence Embedding</strong></p><p><strong>2. Supervised Finetuning:</strong><br>With a domain-pretrained embedding model as the foundation, the process of supervised finetuning for semantic similarity tasks involves refining the model on task-specific data. In this case, the focus is on enhancing semantic similarity. The model undergoes finetuning using labeled data comprising both positive and negative sentence pairs. Positive pairs aid the model in learning to represent embeddings that are closer in distance for similar sentences, while negative pairs guide the model to represent embeddings that are further apart for dissimilar or irrelevant sentences. This targeted approach not only optimizes the model’s performance for semantic similarity tasks but also enhances its ability to discern and differentiate between varying degrees of similarity within the data.<br>Here are some of the techniques:<br><strong>i. GenQ<br>ii. GPL</strong></p><h4>Conclusion</h4><p>In conclusion, building a search engine tailored to a specific domain can be a challenging task, especially when the results lack the desired relevance and finesse. However, by training a domain-specific embedding model, you can unlock the true potential of your domain and improve the search results’ quality.<br>The embedding model is crucial in understanding the nuances of your domain, and by training it with the right data, you can ensure that it captures the unique characteristics of your domain. This will help you to provide more relevant and accurate search results, enhancing the user experience and engagement.<br>In summary, domain-specific embedding models are a powerful tool for improving the performance of search engines in specific domains. By investing time and resources in training and refining your embedding model, you can provide a better search experience for your users and gain a competitive advantage in your field. So, don’t settle for mediocre search results, and start exploring the possibilities of domain-specific embedding models today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2b51f037d17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Sinusoidal Positional Encoding in Transformers]]></title>
            <link>https://medium.com/@pranay.janupalli/understanding-sinusoidal-positional-encoding-in-transformers-26c4c161b7cc?source=rss-ff450d4f6179------2</link>
            <guid isPermaLink="false">https://medium.com/p/26c4c161b7cc</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[positional-encoding]]></category>
            <category><![CDATA[transformer-architecture]]></category>
            <dc:creator><![CDATA[Pranay Janupalli]]></dc:creator>
            <pubDate>Sun, 14 Apr 2024 04:52:56 GMT</pubDate>
            <atom:updated>2024-04-14T04:52:56.761Z</atom:updated>
            <content:encoded><![CDATA[<p>In NLP, transformer architecture has emerged as a powerful architecture for handling sequential data. However, unlike recurrent neural networks (RNNs), transformers lack an inherent mechanism to handle the order of tokens in a sequence. To overcome this limitation, transformers utilize positional encoding, which provides the model with information about the order of tokens in a sequence. In this blog post, we will delve into the concept of positional encoding, focusing on sinusoidal positional encoding, which was introduced in the “<a href="https://arxiv.org/pdf/1706.03762.pdf">Attention is All You Need</a>” paper.</p><h3>What is Sinusoidal Positional Encoding?</h3><p>Sinusoidal positional encoding is a method that adds positional encodings to embeddings at the start of encoder/decoder stacks. It uses sinusoidal functions with different frequencies to encode the position of each element in a sequence. The sine and cosine functions are used to represent the even and odd positions, respectively, in the sequence. This method is based on the idea that the position of a token can be represented as a series of sine and cosine functions with different frequencies, where each frequency corresponds to a different position in the sequence.</p><p>The sine and cosine functions are chosen because they have a cyclic nature, which allows them to return information about the position of a token in a way that is easy for the model to learn. The positional encoding is calculated using a geometric progression of frequencies, where the frequency of the sine and cosine functions increases exponentially as the position in the sequence increases. This allows encoding sequences by relative positions, since for any fixed offset k, PE(pos+k) can be represented as a linear function of PE(pos).</p><p>Lets take a look at the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*2TV5KsoJRfIEyZkjEX-dfw.png" /><figcaption>Positional encoding formula</figcaption></figure><h3>The Significance of 10000 in Sinusoidal Positional Encoding</h3><p>The choice of the value 10000 in the denominator of the sinusoidal positional encoding in transformer models is related to the wavelength of the sinusoidal functions used to represent the position of tokens in a sequence. The wavelengths form a geometric progression from 2π to 10000 · 2π, which means that the distance between the peaks of the sinusoidal functions increases exponentially as the position in the sequence increases.<br>The value 10000 was chosen because it allows the model to represent the position of tokens in a way that is easy for the model to learn, while also providing a unique vector representation for each position in the sequence. The choice of this value is not arbitrary, but rather it is based on the intuition that a large wavelength allows the model to represent the position of tokens in a way that is easy for the model to learn, while also providing a unique vector representation for each position in the sequence.</p><h3>Mathematical Deep Dive:</h3><p>Let’s consider the denominator term, which is calculated as 10000**(2i/dim), where 2i is the dimension in the embedding, dim is the embedding dimension, and 10000 is the value chosen for the geometric progression.<br>The power term, 2i/dim, forms an arithmetic progression (AP) from 0 to (dim/2)-1, which is then converted to a geometric progression (GP) by raising it to the power of 10000. The inverse of this GP is also in GP, and when multiplied with the positions (0,1,…,seq_len), it results in a sequence of values that are then used as input for the sine and cosine functions.</p><h3>Properties of Sinusoidal Positional Encoding:</h3><ul><li><strong>Normalized Range</strong>: The sine and cosine functions used in the encoding keep the values within the range of [-1,1], which is a normalized range that is easy for the model to learn.</li><li><strong>Unique Position Encoding</strong>: Each position is encoded uniquely, enabling the model to distinguish between different positions effectively. It also virtually scales to unlimited sequence lengths.</li><li><strong>Relative distance</strong>: The sinusoidal positional encoding maintains relative distance between positions. For example, the angle between the encodings of position 5 and 6 is equal to the angle of 6 and 7, which represents the relative distance between the positions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*dnr2F0moaY4OpdNSiKRPSw.png" /><figcaption>relative distance matrix for 64 sequence length positional encoding</figcaption></figure><h3>Conclusion:</h3><p>In conclusion, positional encoding is an essential component of transformer models, providing the model with information about the order of tokens in a sequence. Sinusoidal positional encoding is a powerful method for encoding the position of tokens, and the choice of the value 10000 is based on a trade-off between the ease of learning and the uniqueness of the vector representation of the position of tokens in a sequence. By understanding the mathematical underpinnings of sinusoidal positional encoding, we can gain a deeper appreciation for the power and versatility of transformer models in NLP.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26c4c161b7cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>