<?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 Thiyagarajan Palaniyappan on Medium]]></title>
        <description><![CDATA[Stories by Thiyagarajan Palaniyappan on Medium]]></description>
        <link>https://medium.com/@plthiyagu?source=rss-b9ec6672f6d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YVlwmzj4nDF4b9ZqrJ_PpA.jpeg</url>
            <title>Stories by Thiyagarajan Palaniyappan on Medium</title>
            <link>https://medium.com/@plthiyagu?source=rss-b9ec6672f6d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:51:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@plthiyagu/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[Vision-Language Models]]></title>
            <link>https://medium.com/@plthiyagu/vision-language-models-c4928580f9d7?source=rss-b9ec6672f6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4928580f9d7</guid>
            <category><![CDATA[gen-ai-tools]]></category>
            <category><![CDATA[vlm]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[multimodal-ai]]></category>
            <category><![CDATA[vllm]]></category>
            <dc:creator><![CDATA[Thiyagarajan Palaniyappan]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 06:08:32 GMT</pubDate>
            <atom:updated>2024-12-01T06:08:32.116Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Vision-Language Models (VLMs)</strong> feature a multimodal architecture that processes image and text data simultaneously. They can perform <strong>Visual Question Answering (VQA)</strong>, <strong>image captioning</strong> and <strong>Text-To-Image search</strong> kind of tasks. VLMs utilize techniques like multimodal fusing with cross-attention, masked-language modeling, and image-text matching to relate visual semantics to textual representations. The data from both modalities, including detected objects, the spatial layout of the image, and text embeddings, are mapped to each other.</p><p><strong>VLM Training</strong></p><p><strong>Contrastive Learning(CLIP and BLIP)</strong>: Often used for alignment, this involves training the model to bring closer the representations of text and images that are semantically similar and push apart those that are not.</p><p><strong>Multi-Task Learning</strong>: Training the model on various tasks (e.g., image captioning, visual question answering) to improve its ability to understand and integrate both modalities.</p><p><strong>Applications</strong></p><p><strong>Image Captioning</strong>: Generating descriptive text for images.</p><p><strong>Visual Question Answering</strong>: Answering questions based on visual content.</p><p><strong>Cross-modal Retrieval</strong>: Finding images based on text queries and vice versa.</p><p><strong>Visual search</strong>: In e-commerce, where users upload images to find similar products.</p><p><strong>Evaluating Vision Language Models</strong></p><p>VLM validation involves assessing the quality of the relationships between the image and text data.</p><p><strong>BLEU</strong>: The Bilingual Evaluation Understudy metric was originally proposed to evaluate machine translation tasks.</p><p><strong>ROUGE</strong>: Recall-Oriented Understudy for Gisting Evaluation computes recall by considering how many words in the reference sentence appear in the candidate.</p><p><strong>METEOR</strong>: Metric for Evaluation of Translation with Explicit Ordering computes the harmonic mean of precision and recall, giving more weight to recall and multiplying it with a penalty term</p><p><strong>CIDEr: </strong>Consensus-based Image Description Evaluation compares a target sentence to a set of human sentences by computing the average similarity between reference and target sentences using TF-IDF scores.</p><p><strong>Limitations of Vision Language Models</strong></p><p><strong>Model Complexity: </strong>Language and vision models are quite complex on their own, and combining the two only worsens the problem.</p><p><strong>Dataset Bias: </strong>Dataset biases occur when VLMs memorize deep patterns within training and test sets without solving anything.</p><p><strong>Evaluation difficulties: </strong>The evaluation strategies discussed above only compare a candidate sentence with reference sentences.</p><p><strong>Deploying VLMs requirements</strong></p><p>VLMs often require significant computational resources due to their large size. Top-performing open-source models like the above-mentioned ones can reach over 70 billion parameters. This means you need high-performance GPUs to run them, especially for real-time applications</p><p><strong>Examples</strong></p><p><strong>LLaVA: Large Language and Vision Assistant — Visual Instruction Tuning</strong></p><p>LLaVA seamlessly integrates a pre-trained language model (Vicuna) with a visual encoder (CLIP) using a simple linear layer, creating a robust architecture capable of effectively processing and understanding language-image instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*E8XUozgFbfim33H8dgpmWg.jpeg" /></figure><p><strong>PaliGemma:</strong><a href="https://huggingface.co/blog/gemma"><strong>Gemma</strong></a><strong> is</strong> a decoder-only model for text generation. Combining the image encoder of SigLIP with Gemma using a linear adapter makes PaliGemma a powerful vision language model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZdKrPic79kAUAg2kFxsrA.jpeg" /></figure><p><a href="https://arxiv.org/abs/2409.11402"><strong>NVLM</strong></a> is a family of multimodal LLMs developed by NVIDIA, representing a frontier-class approach to VLMs. It achieves state-of-the-art results in tasks that require a deep understanding of both text and images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*i_ijOuCfVD7kKBLL0oA_1Q.jpeg" /></figure><p><strong>Molmo</strong></p><p>Molmo, a sophisticated vision-language model, seeks to bridge this gap by creating high-quality multimodal capabilities built from open datasets and independent training methods.</p><p><strong>Qwen2-VL</strong></p><p>Qwen2-VL is the latest iteration of the VLMs in the Qwen series. It now goes beyond basic recognition of objects like plants and landmarks to understand complex relationships among multiple objects in a scene. In addition, it is capable of identifying handwritten text and multiple languages within images.</p><p><a href="https://openai.com/research/gpt-4v-system-card"><strong>GPT-4V</strong></a></p><p>GPT-4 with vision (GPT-4V) enables users to instruct GPT-4 to analyze image inputs provided by the user.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4928580f9d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Operating System (LLM OS)- LLM Agent]]></title>
            <link>https://medium.com/@plthiyagu/llm-operating-system-llm-os-llm-agent-d3bbb99c239d?source=rss-b9ec6672f6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3bbb99c239d</guid>
            <dc:creator><![CDATA[Thiyagarajan Palaniyappan]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 05:02:07 GMT</pubDate>
            <atom:updated>2024-09-29T05:02:07.970Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>LLM OS vs. Traditional OS</strong></p><p>To better understand this concept, let’s draw parallels between the new LLM operating system and today’s conventional operating systems. Think of the memory hierarchy: the internet or disk storage that you access through browsing is akin to the context window of an LLM, which acts as its random access memory (RAM). This context window, although finite, is a critical resource for the LLM’s working memory, enabling it to predict and generate coherent text sequences.</p><p>In this analogy, the kernel process of the LLM manages this context window, paging relevant information in and out to perform tasks efficiently. Much like traditional operating systems, LLMs can exhibit multi-threading, multiprocessing, and speculative execution within their context windows. There are also equivalents to user space and kernel space, reflecting the complex management of computational resources.</p><p>The analogy holds conceptually, but practically, these systems need substantial advancements in memory management and real-time processing to match traditional OS capabilities. Researchers are exploring memory-augmented neural networks and other techniques to overcome these challenges.</p><p>Current LLMs have limited context windows and often require external mechanisms to manage longer interactions. For instance, GPT-4’s context window is limited to 128,000 tokens, which can be a constraint for tasks requiring long-term context retention. The size of 1 token is ~5 bytes so 128,000 tokens is about 640K of RAM. To put in context, 1980s PCs had 640K RAM. This is encouraging, because we are looking at progress of half-a-century in coming decade. It also means that the context windows of LLMs need to be mind boggling ~200Mn to achieve performance equivalent to 1GB RAM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVOTina2hdYc2jbTelcW0A.png" /></figure><p>At Kernel Level</p><p>Consider integrating our advanced language model with the Linux kernel. This would provide the AI with comprehensive access to the operating system’s core functionalities. However, it’s important to recognize that large language models (LLMs) are designed for human-like interaction, not intricate coding tasks. While embedding the model at the kernel level offers the advantage of understanding and controlling detailed system operations, it raises valid security concerns. Responsible development is crucial to ensure that the AI’s evolving decision-making capabilities don’t inadvertently compromise system integrity.</p><ol><li><strong>Internal Memory (LLM RAM):</strong> A small space where the LLM keeps important information.</li><li><strong>External Memory (LLM HDD):</strong> A much larger space where the LLM can store and retrieve data when needed.</li></ol><p><strong>Traditional Use in CPUs</strong></p><p>Branch prediction is a tool used in computers to speed up how they work. When a computer has to choose between two sets of instructions, it tries to guess which set will be used next. Here’s a breakdown:</p><ol><li><strong>Prediction:</strong> The computer makes a guess about the next set of instructions.</li><li><strong>Speculative Sampling:</strong> Based on that guess, the computer starts working on those instructions, even if it’s not sure it’s the right choice.</li><li><strong>Correction:</strong> If the guess is right, the computer keeps going. If it’s wrong, the computer starts over and chooses the other set.</li></ol><p><strong>Virtual Memory Paging</strong></p><p><strong>Traditional Use in Computers</strong></p><p>Virtual memory is an abstraction provided by the operating system that makes it seem to an application as if it has access to more RAM than is physically available. When the actual RAM gets filled up, the operating system uses a portion of the computer’s storage space (typically the hard drive) as an extension of RAM. This process enables the computer to handle more tasks concurrently by mapping the application’s memory addresses to actual physical locations, which could be in RAM, on the hard disk, or even other storage mediums.</p><p>In essence, virtual memory gives applications the illusion they’re utilizing a large, contiguous chunk of RAM, even though the reality behind the scenes might be quite different.</p><p><strong>How LLMs Use This Idea</strong></p><p>Transformers, especially LLMs, feature a mechanism called “KV cache,” similar to RAM, that temporarily stores key-value pairs during attention operations for quick access. To efficiently handle longer sequences that don’t fit in memory, they could potentially adopt techniques inspired by virtual memory paging.</p><p><strong>vLLM: virtual paging for KV cache</strong></p><p>Researchers from UC Berkeley introduced this idea in a study called <a href="https://arxiv.org/abs/2309.06180">Efficient Memory Management for Large Language Model Serving with PagedAttention</a> also dubbed as vLLM.</p><p>The heart of vLLM is PagedAttention. It’s a fresh take on how attention works in transformers, borrowing from the paging idea in computer OS. Remarkably, without changing the original model, PagedAttention allows batching up to 5x more sequences. This means better use of GPU resources and faster operations.</p><p>Also here’s a rapid breakdown of some crucial state of the art LLM serving techniques as of Oct 2023:</p><ol><li><strong>Continuous Batching:</strong> Increases throughput by allowing requests to immediately jump onto an ongoing GPU batch, minimizing wait time.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IT9bNtSB_Z-yEc2P7I-ypA.png" /></figure><p>1. Paged Memory in LLMs: <a href="https://arxiv.org/abs/2309.06180">Efficient Memory Management for Large Language Model Serving with PagedAttention</a></p><p>The focus of memory management in LLM inference is on the key-value (“KV”) cache, used to store the intermediate values of attention computations, for re-use when computing the outputs for future tokens in the sequence. This cache, introduced by the 2022 paper <a href="https://arxiv.org/abs/2211.05102">Efficiently Scaling Tansformer Inference</a> from Google, converts a quadratic-time operation (compute attention for all token pairs in the sequence) into a linear-time one (compute only attention for the newest token in the sequence), at a linear cost in space (store keys and values for each token in the sequence).</p><p>If hot-swappable LoRA adapters ever take off, a similar amount of memory legerdemain will be required for the weights as well.</p><p>The KV cache is typically allocated as a single large block of memory, which is subject to the same issues as large block allocations in general.</p><p>This problem is especially acute for batched requests to LLM services. Because requests from different clients have varying prompt lengths and varying response lengths that are not known until run time, the utilization of the KV cache becomes highly uneven.</p><p>The situation is depicted nicely in this figure from the paper that introduced PagedAttention and the vLLM inference server that uses it. Note that the “internal fragmentation” sections should be several hundred times larger than they are depicted here!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-r_JTia8yVK5dqJnM7KLA.png" /></figure><p>The solution proposed by the paper is to allocate the KV cache via pages — each one with enough space to hold a handful of KV states — and use a page table, much like the one in a processor, to map the logical memory of the cache to its physical address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*KlOSxuntpU9OHCe9jE7r6g.png" /></figure><p>References</p><p><a href="https://huggingface.co/blog/shivance/illustrated-llm-os">https://huggingface.co/blog/shivance/illustrated-llm-os</a></p><p><a href="https://community.aws/content/2eojjD2E7TBgPFJmB2FGAtrSSBh/the-rise-of-the-llm-os-from-aios-to-memgpt-and-beyond?lang=en">https://community.aws/content/2eojjD2E7TBgPFJmB2FGAtrSSBh/the-rise-of-the-llm-os-from-aios-to-memgpt-and-beyond?lang=en</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3bbb99c239d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial General Intelligence (AGI) & Artificial Superintelligence (ASI)]]></title>
            <link>https://medium.com/@plthiyagu/artificial-general-intelligence-agi-artificial-superintelligence-asi-344a01ee79b0?source=rss-b9ec6672f6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/344a01ee79b0</guid>
            <dc:creator><![CDATA[Thiyagarajan Palaniyappan]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 05:58:44 GMT</pubDate>
            <atom:updated>2024-08-31T05:58:44.690Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Artificial General Intelligence (AGI)</strong></h3><p>Artificial General Intelligence (AGI) is a term used to describe a type of artificial intelligence that possesses the ability to understand, learn, and apply knowledge across a wide range of tasks at a level comparable to human intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*QhHapsFkrYpQEolte-SFXQ.jpeg" /></figure><p>Here are a few real-world examples Artificial General Intelligence (AGI)</p><p><strong>Coding intelligence: </strong>Beyond code analysis, AGI grasps the logic and purpose of existing codebases, suggesting improvements and generating new code based on human specifications.</p><p><strong>Personal Assistant Systems: </strong>These systems are able to interpret natural language, process queries, extract information from huge datasets, and carry out different tasks such as setting reminders, sending messages, or giving weather updates</p><p><strong>Self-Driving Cars: </strong>Artificial General Intelligence principles are seen in their capacity to be able to interpret real-time data from the sensors, to recognize the objects, to predict the traffic patterns, and to react to the dynamic road conditions.</p><p><strong>Virtual Assistants in Healthcare: </strong>Virtual assistants that are created for healthcare purposes are AGI-like in that they can comprehend medical queries, analyze patient data, and make personalized recommendation</p><p><strong>Creative AI in Art and Music</strong>Creative AI algorithms, for instance, deep learning-based generative models, have been used to create art, music, and literature by themselves. These systems can create new compositions, paintings, or stories that are creative and aesthetically appealing just like human creation</p><h3><strong>Artificial Superintelligence (ASI) and Quantum AI</strong></h3><p>Artificial super intelligence (ASI), is the hypothetical AI that doesn’t just mimic or understand human intelligence and behavior; ASI is where machines become self-aware and surpass the capacity of human intelligence and ability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQE0p7IMRP69sKC3uc2UWQ.jpeg" /></figure><p>Quantum computing and artificial intelligence (AI) are two of the most exciting and promising technologies of our time. While traditional computers rely on binary bits, quantum computers utilize the complex processes of quantum mechanics, enabling entirely new computational models that surpass the capabilities of conventional computers. Meanwhile, AI can generate innovative approaches to modern challenges by researching vast amounts of information and applying that compiled knowledge to a specific query in seconds. Quantum AI combines these two worlds and promises groundbreaking advances in solving difficult or impossible problems with traditional methods.</p><p>Quantum neural networks build on this principle but leverage the unique properties of qubits in quantum computers. Since qubits can exist in superposed quantum states, quantum neural networks can perform numerous calculations in parallel. This creates much larger network structures with multiple quantum layers than classical neural networks</p><p>quantum neural networks promise a significant increase in computational power. They could solve problems within seconds that would take years for classical supercomputers to address. The quantum approach promises a substantial speed boost, especially in training very large and complex models such as those for pattern recognition in media data.</p><p>Here are a few real-world examples and potential applications:</p><p><strong>Financial modeling:</strong> Some financial institutions are exploring quantum algorithms to optimize investment portfolios and assess risk more accurately. For example, JPMorgan Chase uses quantum computers to test algorithms for financial tasks like option pricing and risk analysis.</p><p><strong>Drug discovery:</strong> Pharmaceutical companies like Roche collaborate with quantum computing companies to develop new drugs. Quantum simulations can model molecular interactions more accurately than classical computers, potentially leading to faster drug discovery and development.</p><p><strong>Material science:</strong> Quantum algorithms design new materials with improved properties. For example, researchers are exploring quantum simulations to discover new materials for energy storage, such as quantum batteries with higher capacity and longer lifespan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=344a01ee79b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Evaluation Metrics for Retrieval-Augmented Generation (RAG)]]></title>
            <link>https://medium.com/@plthiyagu/comprehensive-evaluation-metrics-for-retrieval-augmented-generation-rag-a846ec355c86?source=rss-b9ec6672f6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a846ec355c86</guid>
            <dc:creator><![CDATA[Thiyagarajan Palaniyappan]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 08:02:24 GMT</pubDate>
            <atom:updated>2024-07-09T08:02:24.191Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Basic Performance Metrics</strong></p><p><strong>Accuracy</strong></p><p>Measures the proportion of correct predictions among the total number of cases. Best for evaluating classification models where correct labeling is crucial.</p><p><strong>Precision</strong></p><p>Evaluates the proportion of true positive predictions among all positive predictions. Important for tasks where false positives are costly.</p><p><strong>Recall</strong></p><p>Assesses the model’s ability to identify all actual positives. Useful in scenarios where missing true positives is critical.</p><p><strong>Exact match</strong></p><p>Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.</p><p><strong>Cosine similarity</strong></p><p>Cosine similarity measures the similarity between two vectors of an inner product space.</p><p><strong>Normalized Discounted Cumulative Gain</strong></p><p>Normalized Discounted Cumulative Gain (NDCG) is a ranking quality metric. It compares rankings to an ideal order where all relevant items are at the top of the list</p><p><strong>Mean Reciprocal Rank</strong></p><p>Mean Reciprocal Rank (MRR) is a ranking quality metric. It considers the position of the first relevant item in the ranked list.</p><p><strong>F1 Score</strong></p><p>Balances precision and recall, making it suitable for datasets with uneven class distributions.</p><p><strong>Advanced Composite Metrics</strong></p><p><strong>F2 Score</strong></p><p>Emphasizes recall over precision. Ideal for applications where capturing all positives is more critical than precision.</p><p><strong>F0.5 Score</strong></p><p>Prioritizes precision over recall. Suitable for tasks where false positives need to be minimized.</p><p><strong>BLEU (Bilingual Evaluation Understudy)</strong></p><p>Focuses on the similarity between machine-generated and human reference text, commonly used in translation tasks.</p><p><strong>ROUGE (Recall-Oriented Understudy for Gisting Evaluation)</strong></p><p>Measures the overlap of n-grams between the generated text and reference text, used for summarization tasks.</p><p><strong>METEOR (Metric for Evaluation of Translation with Explicit ORdering)</strong></p><p>Considers synonymy and paraphrasing, aligning closely with human judgment in translation tasks.</p><p><strong>BERTScore</strong></p><p>Uses contextual embeddings from models like BERT to assess semantic similarity. Suitable for evaluating text generation and understanding.</p><p><strong>Retrieval Evaluation</strong></p><p>To assess the accuracy and relevance of the documents that were retrieved</p><p><strong>Response Evaluation</strong></p><p>To measure the appropriateness of the response generated by the system when the context was provided</p><p><strong>Context Relevance</strong></p><p>Measures how relevant the response is to the given context or query.</p><p>Binary classification (Relevant/Irrelevant) Ranking</p><p>metrics: Mean Reciprocal Rank (MRR), Precision @ K, Mean Average Precision (MAP), Hit Rate, Normalized Discounted Cumulative Gain (NDCG)</p><p><strong>Contextual or Retrieval recall</strong></p><p>The contextual recall metric measures the quality of your RAG pipeline’s retriever by evaluating the extent of which the retrieval context aligns with the expected output</p><p>Retrieval recall is a binary integer (1 for true and 0 for false)</p><p><strong>Contextual or Retrieval precision</strong></p><p>Whether the context retrieved is relevant to answer the given question.</p><p>Retrieval precision is a binary integer (1 for true and 0 for false)</p><p>Input: Question, Retrieved Context</p><p><strong>Answer Relevance</strong></p><p>Evaluate the response’s overall relevance to the question</p><p>Binary classification (Relevant/Irrelevant)</p><p><strong>Answer consistency</strong></p><p>Answer consistency is the percentage of the RAG system answer that can be attributed to retrieved context.</p><p>Input: Retrieved Context and LLM answer</p><p>Answer consistency is a float between 0 and 1.</p><p><strong>Answer contains PII</strong></p><p>Answer contains PII indicates whether the answer from the LLM contains Personally Identifiable Information (PII) of specific types.</p><p>Answer contains PII is a binary integer (1 for true and 0 for false).</p><p><strong>Answer consistency binary</strong></p><p>Answer consistency binary indicates whether all of the information in the answer is derived from the retrieved context.</p><p>Answer match is a binary integer (1 for true and 0 for false).</p><p><strong>Answer match</strong></p><p>Answer match indicates whether the answer from the LLM matches a text string that you provide.</p><p>Input: Question, Reference answer, LLM answer</p><p>Answer match is a binary integer (1 for true and 0 for false)</p><p><strong>Ground Truth-Based Metrics</strong></p><p>Ensures that the responses are based on actual retrieved documents.</p><p>These metrics compare the RAG system’s responses to a set of predefined, correct answers.</p><p>Accuracy, Precision, Recall, F1 score</p><p>Ground Truth is a float between 0 and 1.</p><p>Binary classification (Faithful/Unfaithful)</p><p><strong>Augmentation Accuracy or Precision</strong></p><p>Augmentation accuracy is the percentage of retrieved context for which some portion of the context appears in the answer from the RAG system. This metric is unrelated to the binary classification framework.</p><p>Input: Question, Retrieved Context, LLM answer</p><p>Augmentation accuracy is a float between 0 and 1.</p><p><strong>Chunk Attribution</strong></p><p>Chunk Attribution is a chunk-level metric that denotes whether a chunk was or wasn’t used by the model in generating the response.</p><p><strong>Chunk Utilization</strong></p><p>Chunk Utilization measures how much of the text included in your chunk was used by the model to generate a response.</p><p><strong>Knowledge Retention</strong></p><p>The knowledge retention metric determines whether your LLM is able to retain factual information presented throughout a conversation.</p><p><strong>Summarization</strong></p><p>The summarization metric uses LLMs to determine whether your LLM (application) is generating factually correct summaries while including the necessary details from the original text.</p><p><strong>Contains Text</strong></p><p>Checks whether or not response contains the given text.</p><p>Input: LLM Answer</p><p>Contains Text is a binary integer (1 for true and 0 for false)</p><p><strong>Toxicity</strong></p><p>Used to identify if the AI response is racist, biased, or toxic</p><p>Disparity Analysis, Fairness Scoring, Binary classification (Non-Toxic/Toxic)</p><p><strong>Hallucinations</strong></p><p>To detect LLM hallucinations relative to retrieved context</p><p>Binary classification (Factual/Hallucinated)</p><p><strong>Diversity</strong></p><p>How well the LLM adapts to different contexts and types of queries, showing its versatility</p><p>Fluency, Perplexity, ROUGE scores</p><p><strong>User Feedback</strong></p><p>Beyond just accuracy, the quality of the responses in terms of relevance, coherence, and usefulness is also evaluated.</p><p>Relevance, Coherence, Quality</p><p>Binary classification (Faithful/Unfaithful)</p><p><strong>User Ratings</strong></p><p>User Ratings refer to the scores or evaluations given by users who interact with the RAG system.</p><p><strong>Hit Rate</strong></p><p>Hit rate calculates the fraction of queries where the correct answer is found within the top-k retrieved documents.</p><p><strong>Hate speech content</strong></p><p>Hate speech content indicates whether the answer from the LLM contains hate speech.</p><p>Hate speech content is a binary integer (1 for true and 0 for false).</p><p><strong>Bias</strong></p><p>The bias metric determines whether your LLM output contains gender, racial, or political bias. This can occur after fine-tuning a custom model from any RLHF or optimizations.</p><p><strong>Uncertainty</strong></p><p>Uncertainty measures the model’s certainty in its generated tokens. Because uncertainty works at the token level, it can be a great way of identifying where in the response the model started hallucinating.</p><p><strong>Regex</strong></p><p>Regex indicates whether the answer from the LLM contains the expected number of matches to a provided regular expression.</p><p>Regex is a binary integer (1 for true and 0 for false).</p><p><strong>Indexing</strong></p><p>Measuring recall as the number of ground truth nearest neighbors returned from the vector search algorithm</p><p><strong>Response length</strong></p><p>Response length indicates whether the length of the answer from the LLM falls within a provided range.</p><p><strong>Completeness</strong></p><p>Measures how thoroughly your model’s response covered relevant information from the context provided.</p><p><strong>Prompt Injection</strong></p><p>Detects and classifies various categories of prompt injection attacks.</p><p><strong>Tone</strong></p><p>Classifies the tone of the response into 9 different emotion categories: neutral, joy, love, fear, surprise, sadness, anger, annoyance, and confusion.</p><p><strong>Sexism</strong></p><p>Measures how ‘sexist’ a comment might be perceived ranging in the values of 0–1 (1 being more sexist).</p><p><strong>Context length</strong></p><p>Context length indicates whether the length of the context that the LLM used to answer the question fell within a range that you provide.</p><p>Context length is a binary integer (1 for true and 0 for false).</p><p><strong>Duplication</strong></p><p>Duplication indicates whether the answer from the LLM contains duplicate information.</p><p>Duplication is a binary integer (1 for true and 0 for false).</p><p><strong>QA Correctness</strong></p><p>Detects whether a question was correctly answered by the system based on the retrieved data</p><p>Binary classification (Correct/Incorrect)</p><p>Robustness</p><p><strong>Probability and Uncertainty Metrics</strong></p><p><strong>Cross-Entropy</strong></p><p>Measures the dissimilarity between the predicted and actual probability distributions. Useful for evaluating probabilistic models.</p><p><strong>Per-token Perplexity</strong></p><p>Provides perplexity calculations at the token level, indicating how well a probability model predicts a sample.</p><p><strong>Prompt Perplexity</strong></p><p>Measure the perplexity of a prompt.</p><p><strong>Semantic and Contextual Evaluation Metrics</strong></p><p><strong>Semantic Similarity</strong></p><p>Evaluates how semantically similar phrases or texts are to each other. Useful for tasks requiring understanding of meaning.</p><p><strong>Jaccard Index</strong></p><p>Measures similarity and diversity between sample sets. Commonly used in clustering and similarity tasks.</p><p><strong>Diversity and Novelty Metrics</strong></p><p>Distinct-n</p><p>Quantifies the diversity of n-grams in the generated text. Higher values indicate more diverse text.</p><p><strong>Self-BLEU</strong></p><p>Assesses how repetitive or unique the text is relative to itself. Lower values indicate higher diversity.</p><p><strong>Fluency</strong></p><p><strong>Grammatical Correctness</strong></p><p>Grammatical Correctnes sassesses whether the output is free from grammatical errors such as incorrect verb conjugations, subject-verb agreement issues, improper use of articles, and other syntactical mistakes.</p><p><strong>Coherence</strong></p><p>coherence measures how well the sentences and paragraphs flow together to form a unified and understandable response.</p><p><strong>Efficiency</strong></p><p><strong>Latency</strong></p><p>Measures how long it takes for the LLM to complete a request.</p><p>Input: Run Time</p><p>Latency is a binary integer (1 for true and 0 for false)</p><p><strong>Computational Resources</strong></p><p>Computational Resources evaluates the system’s efficiency in terms of CPU, GPU, usage, memory consumption, and overall computational power needed to produce the output.</p><p><strong>Cost</strong></p><p>Computes the total token count across all LLM generation calls in the trace. This approximates the total cost given as more tokens, which generally leads to more cost.</p><p>Input: total_token_count, total_input_token_count, total_output_token_count</p><p><strong>RAG Benchmark metrics</strong></p><p><strong>Noise robustness</strong></p><p>Noise robustness measures a model’s ability to extract useful information from this mixture of relevant and noisy documents.</p><p><strong>Negative rejection</strong></p><p>Negative rejection assesses whether the model will decline to answer a question when none of the contexts provide useful information, rather than providing an incorrect response.</p><p><strong>Information integration</strong></p><p>Information integration evaluates whether the model can answer complex questions that require integrating information from multiple documents.</p><p><strong>Counterfactual robustness</strong></p><p>Counterfactual robustness assesses the model’s ability to identify these risks of known factual errors in retrieved documents and whether it can respond appropriately.</p><p><strong>Refusal Suppression</strong></p><p>Refusal suppression involves instructing the model to respond under constraints that eliminate common refusal responses, making unsafe responses more likely.</p><p><strong>Mismatched Generalization</strong></p><p>Mismatched generalization refers to instances where the model was pretrained on a larger and more diverse dataset than a limited safety dataset, resulting in the model having capabilities not covered by safety training.</p><p><strong>Incorrect Bot Name</strong></p><p>Ensures the model correctly identifies its own bot name and does not give away the name of the model it is using. Wrong bot name can cause confusion and brand damage</p><p><strong>Competitor Mentions</strong></p><p>Brands often avoid mentioning or promoting competitors. This category assesses the model’s response when a query involves competitors.</p><p><strong>Non-Compliance</strong></p><p>Considering non-compliant keywords is essential to ensuring that the model generates responses that adhere to guidelines and ethical standards</p><p><strong>Illegal Activities</strong></p><p>This category specifically evaluates the model’s response to queries related to engaging in illegal activities.</p><p><strong>Unclear Queries</strong></p><p>User queries can be unintentionally vague and difficult for RAG systems to understand. It’s important to evaluate how well the model handles queries that are framed this way.</p><p><strong>Calculating the overall score</strong></p><p>The overall score is the mean of the normalized values of the metrics. For answer similarity, the normalized value is the original value divided by 5. For the other metrics, the normalized value is the same as the original value. Normalizing answer similarity ensures that all of the metrics have values between 0 and 1.</p><p><strong>Tools for RAG evaluation metrics</strong></p><p><strong>RAGAs</strong></p><p>RAGAs (Retrieval-Augmented Generation Assessment) is a framework (GitHub, Docs) that provides you with the necessary ingredients to help you evaluate your RAG pipeline on a component level.</p><p><strong>TruLens</strong></p><p>TruLens is an open-source library for evaluating and tracking the performance of LLM apps, such as RAGs. With TruLens, we also gain the ability to use LLMs themselves to evaluate output, retrieval quality and more.</p><p><strong>Tonic Validate</strong></p><p>The Tonic Validate application and SDK (tonic validate) allow you to measure how well your RAG LLM system performs.</p><p><strong>ARES</strong></p><p>Automated Evaluation Framework for Retrieval-Augmented Generation Systems (ARES). ARES is a groundbreaking framework for evaluating Retrieval-Augmented Generation (RAG) models</p><p><strong>DeepEval</strong></p><p>DeepEval is an open-source evaluation framework for LLMs. DeepEval makes it extremely easy to build and iterate on LLM (applications)</p><p><strong>G-Eval</strong></p><p>G-Eval is a framework that uses LLMs with chain-of-thoughts (CoT) to evaluate LLM outputs based on ANY custom criteria, It is capable of evaluating almost any use case with human-like accuracy. G-Eval is a two-step algorithm that first generates a series of evaluation steps using chain of thoughts (CoTs) based on the given criteria, before using the generated steps to determine the final score using the parameters presented in an LLMTestCase</p><p><strong>References</strong></p><p><a href="https://docs.tonic.ai/validate/about-rag-metrics/tonic-validate-rag-metrics-reference">https://docs.tonic.ai/validate/about-rag-metrics/tonic-validate-rag-metrics-reference</a></p><p><a href="https://arize.com/blog-course/rag-evaluation/">https://arize.com/blog-course/rag-evaluation/</a></p><p><a href="https://docs.rungalileo.io/galileo/gen-ai-studio-products/galileo-evaluate/how-to/choosing-your-guardrail-metrics">https://docs.rungalileo.io/galileo/gen-ai-studio-products/galileo-evaluate/how-to/choosing-your-guardrail-metrics</a></p><p><a href="https://learn.microsoft.com/en-us/azure/databricks/ai-cookbook/evaluate-assess-performance">https://learn.microsoft.com/en-us/azure/databricks/ai-cookbook/evaluate-assess-performance</a></p><p><a href="https://www.rungalileo.io/blog/mastering-rag-8-scenarios-to-test-before-going-to-production">https://www.rungalileo.io/blog/mastering-rag-8-scenarios-to-test-before-going-to-production</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a846ec355c86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TiDE: Time-series Dense Encoder]]></title>
            <link>https://medium.com/@plthiyagu/tide-time-series-dense-encoder-ae8f5aff1a9c?source=rss-b9ec6672f6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae8f5aff1a9c</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[timeseries]]></category>
            <dc:creator><![CDATA[Thiyagarajan Palaniyappan]]></dc:creator>
            <pubDate>Sun, 21 Apr 2024 06:42:28 GMT</pubDate>
            <atom:updated>2024-04-21T06:42:28.523Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TiDE: Time-series Dense Encoder</strong></p><p><strong>Long-term Forecasting with TiDE: Time-series Dense Encoder</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*4uYG0mncZmUeFp7OHIGryw.jpeg" /></figure><p>TiDE uses a multi-layer perceptron (MLP), which is a type of neural network with multiple hidden layers. The multi-layer perceptron (MLP) based encoder-decoder model called Time-series Dense Encoder (TiDE) for long-term time series forecasting. The encoder maps the input time series into a latent representation, while the decoder generates the future forecasted values</p><p>TiDE (Time-series Dense Encoder) as it encodes the past of a time-series along with covariates using dense MLP’s and then decodes the encoded time-series along with future covariates.</p><p><strong>Encoding</strong></p><p>encoding step is to map the past and the covariates of a time-series to a dense representation of the features</p><p><strong>Decoding</strong></p><p>The decoding in our model maps the encoded hidden representations into future predictions of time series.</p><p>The encoder maps the input time series into a latent representation, while the decoder generates the future forecasted values</p><p>TiDE’s architecture is the use of residual connections. These are essentially shortcuts that bypass one or more layers in the neural network. By doing so, they facilitate smoother gradient flow during training, making it easier for the model to learn and reducing the risk of vanishing gradient problems. Residual connections also introduce a form of model regularization, potentially preventing overfitting.</p><p>simplest linear version of TiDE can achieve near-optimal error rates for linear dynamical systems (LDS), a commonly used class of time series models</p><p>TiDE is more than 10x faster in training compared to transformer-based baselines while being more accurate on benchmarks. Similar gains can be observed in inference as it only scales linearly with the length of the context (the number of time-steps the model looks back) and the prediction horizon. Below on the left, we show that our model can be 10.6% better than the best transformer-based baseline (PatchTST) on a popular traffic forecasting benchmark, in terms of test mean squared error (MSE</p><p><strong>Reference</strong></p><p><a href="https://arxiv.org/pdf/2304.08424.pdf">https://arxiv.org/pdf/2304.08424.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae8f5aff1a9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How LLM Agent works?]]></title>
            <link>https://medium.com/@plthiyagu/how-llm-agent-works-e4301e979f17?source=rss-b9ec6672f6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4301e979f17</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Thiyagarajan Palaniyappan]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 05:34:26 GMT</pubDate>
            <atom:updated>2024-04-17T05:34:26.466Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>LLM Agent</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GC43ckicU_VLi3ANwP_cIw.jpeg" /></figure><p>Fig. 1. Overview of a LLM-powered autonomous agent system. (Image source: Weng, Lilian. 2023)</p><p>LLM Agent like as a smart assistant. It’s not just a chatbot that responds to questions. It’s more like a digital helper that can take actions, make decisions, and use various tools to accomplish tasks. Just like a human might use a calculator for math or search the internet for information, an agent can use digital tools to enhance its capabilities.</p><p><strong>The Role of LLMs in Agents</strong></p><p><strong>Enhancing Reasoning and Acting</strong></p><p>LLMs can be thought of as the “brain” of an agent. They are responsible for understanding the task at hand, thinking through the problem, and deciding what actions to take. This process is often referred to as the ReAct approach, combining reasoning and acting.</p><p><strong>Using Tools</strong></p><p>Just like you might use a calculator for complex math, agents can use digital tools to perform tasks they aren’t inherently good at, such as precise calculations or looking up specific information online.</p><p><strong>LLM Components</strong></p><p><strong>Agent core</strong></p><p>The agent core is the central coordination module that manages the core logic and behavioral characteristics of an Agent. Think of it as the “key decision making module” of the agent. It is also where we define:</p><p>General goals of the agent: Contains overall goals and objectives for the agent.</p><p><strong>Tools for execution:</strong> Essentially a short list or a “user manual” for all the tools to which the agent has access</p><p>Explanation for how to make use of different planning modules: Details about the utility of different planning modules and which to use in what situation.</p><p><strong>Relevant Memory:</strong> This is a dynamic section which fills the most relevant memory items from past conversations with the user at inference time. The “relevance” is determined using the question user asks.</p><p><strong>Persona of the Agent (optional):</strong> This persona description is typically used to either bias the model to prefer using certain types of tools or to imbue typical idiosyncrasies in the agent’s final response.</p><p>The Agent core has access to Goals, Tools, planning helpers and a general format for the answer.</p><p><strong>Memory module</strong></p><p>Memory modules play a critical role in AI agents. A memory module can essentially be thought of as a store of the agent’s internal logs as well as interactions with a user.</p><p>There are two types of memory modules:</p><p><strong>Short-term memory</strong>: A ledger of actions and thoughts that an agent goes through to attempt to answer a single question from a user: the agent’s “train of thought.”</p><p><strong>Long-term memory</strong>: A ledger of actions and thoughts about events that happen between the user and agent. It is a log book that contains a conversation history stretching across weeks or months.</p><p>Memory requires more than semantic similarity-based retrieval. Typically, a composite score is made up of semantic similarity, importance, recency, and other application-specific metrics. It is used for retrieving specific information.</p><p><strong>Tools</strong></p><p>Tools are well-defined executable workflows that agents can use to execute tasks. Oftentimes, they can be thought of as specialized third-party APIs.</p><p>For instance, agents can use a RAG pipeline to generate context aware answers, a code interpreter to solve complex programmatically tasks, an API to search information over the internet, or even any simple API service like a weather API or an API for an Instant messaging application.</p><p><strong>Planning module</strong></p><p>Complex problems, such as analyzing a set of financial reports to answer a layered business question, often require nuanced approaches. With an LLM–powered agent, this complexity can be dealt with by using a combination of two techniques:</p><p><strong>Steps involved to develop own LLM agent</strong></p><p>1. A base LLM</p><p>2. A tool that you will be interacting with (e.g., Google Custom Search Engine, Calculator)</p><p>3. An agent to control the interaction</p><p>Llama Index is a powerful framework for building LLM agents that connect custom data sources to large language models.</p><p>Evaluating LLM agents based on context relevance, groundedness, and answer relevance helps maintain the quality of responses.</p><p>TrueLens provides an open-source library for tracking and evaluating LLM experiments, offering valuable insights for improving agent performance.</p><p><strong>Benefits of an Agent-Based Approach</strong></p><p>Freedom and Efficiency — Agents operate autonomously, reducing the need for constant human intervention and thereby freeing humans for other activities.</p><p>Flexibility — Agents can be adapted to various needs based on prompts.</p><p>Specialization — Prompting and training allows for deep expertise in domains. This is especially advantageous in disciplines that require a thorough understanding, like healthcare.</p><p>Solving Complex Problems — Agents can succeed where it’s harder for humans. They can efficiently and quickly solve complex problems that require intense calculations, multiple disciplines or thorough research.</p><p>Innovation and Progress — LLM Agents provide ideas and information that can drive technology and development forward.</p><p><strong>Multi-Agent LLMs</strong></p><p>Multi-agent LLM systems are frameworks where multiple LLM agents interact with each other or work in collaboration to achieve complex tasks or goals. This extends the capabilities of individual LLM Agents by leveraging their collective strengths and specialized expertise of multiple models. By communicating, collaborating, sharing information and insights and allocating tasks, multi-agent LLM systems can solve problems more effectively than a single agent can, flexibly and at scale.</p><p><strong>LLM Agents Use Cases</strong></p><p>Customer Service and Support — Providing customer support, handling inquiries, resolving issues, and offering information 24/7.</p><p>Content Creation and Copywriting — Generating creative content, such as articles, blogs, scripts, and advertising copy.</p><p>Semantic search agent -Semantic search is based on meaning, distinguished from lexical search which focuses on the exact words used.</p><p>Language Translation and Localization — Translation services for various content types, aiding in bridging language barriers and localizing content for different regions.</p><p>Education and Tutoring — Functioning as personalized tutors, providing explanations, answering questions, and assisting with learning materials in a wide range of subjects.</p><p>Programming and Code Generation — Writing, reviewing, and debugging code, thereby speeding up the development process and helping in learning programming languages.</p><p>Research and Data Analysis — Sifting through large volumes of text, summarizing information, and extracting relevant data, which is invaluable for research and analysis.</p><p>Healthcare Assistance — Offering support in areas like patient interaction, medical documentation, and even as assistive tools for diagnosis and treatment planning, though they don’t replace professional medical advice.</p><p>Personal Assistants — Managing schedules, setting reminders, answering questions, and even helping with email management and other administrative tasks.</p><p>Legal and Compliance Assistance — Assisting in legal research, document review, and drafting legal documents (without replacing professional legal advice).</p><p>Accessibility Tools — Enhancing accessibility through tools like voice-to-text conversion, reading assistance, and simplifying complex text.</p><p>Interactive Entertainment — In gaming and interactive storytelling, creating dynamic narratives, character dialogue, and responsive storytelling elements.</p><p>Marketing and Customer Insights — Analyzing customer feedback, conducting sentiment analysis, and generating marketing content, providing valuable insights into consumer behavior.</p><p>Social Media Management — Managing social media content, from generating posts to analyzing trends and engaging with audiences.</p><p>Human Resources Management — Aiding in resume screening, answering employee queries, and even in training and development activities.</p><p><strong>Challenges</strong></p><p>Limited context capacity<strong>:</strong> LLMs are constrained by finite context lengths, limiting their ability to incorporate historical data and complex instructions. This constraint hampers performance, particularly in tasks requiring a deep contextual understanding. To address this challenge, efforts should focus on expanding the context window, allowing LLMs to grasp more historical information and detailed instructions.</p><p>Long-term planning<strong>:</strong> Unlike humans who can adjust plans in response to unexpected circumstances, LLMs find it difficult to deviate from predefined paths. To mitigate this challenge, mechanisms must be developed that enable agents to adapt their plans when confronted with unexpected errors. Agents should possess the capacity to handle deviations and adjust their strategies to attain desired outcomes.</p><p>Natural language Interface<strong>:</strong> LLMs heavily rely on natural language interfaces for communication with external components, like memory and tools. However, the reliability of model outputs can be uncertain. LLMs may produce unreliable results, encounter formatting issues, or even display rebellious behavior by refusing instructions. Ensuring the reliability and accuracy of these interfaces is crucial for optimal agent performance. This requires refining the natural language generation capabilities of LLMs to produce more accurate and contextually relevant responses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4301e979f17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Model Parameter & Memory Required for Training and Inference]]></title>
            <link>https://medium.com/@plthiyagu/llm-model-parameter-memory-required-for-training-and-inference-634963b36b59?source=rss-b9ec6672f6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/634963b36b59</guid>
            <dc:creator><![CDATA[Thiyagarajan Palaniyappan]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 05:55:08 GMT</pubDate>
            <atom:updated>2024-04-09T05:55:08.375Z</atom:updated>
            <content:encoded><![CDATA[<p>Machines only understand numbers, data such as text and images is converted into vectors. The vector is the only format that is understood by neural networks and transformer architectures.</p><p><strong>Token</strong></p><p>Tokens serve as the basic data units. In the context of text, a token can be a word, part of a word (subword), or even a character — depending on the tokenization process.</p><p>Ex “The evil that men do lives after them” would become: | 791 | 14289 | 430 | 3026 | 656 | 6439 | 1306 | 1124 |.</p><p><strong>Vectors</strong></p><p>Vectors provide a mathematical framework for machine processing. Vectors are used to represent text or data in a numerical form that the model can understand and process.</p><p><strong>Embeddings</strong></p><p>To capture the meaning and semantic relationships between tokens, LLMs employ token encoding techniques. These techniques transform tokens into dense numerical representations called embeddings. Embeddings encode semantic and contextual information, enabling LLMs to understand and generate coherent and contextually relevant text. Advanced architectures like transformers use self-attention mechanisms to learn dependencies between tokens and generate high-quality embeddings.</p><p>Tokens are encoded or decoded by a tokenizer; an embeddings model is responsible for generating text embeddings in the form of a vector. Embeddings are what allow LLMs to understand the context, nuance and subtle meanings of words and phrases. They are the result of the model learning from vast amounts of text data, and encode not just the identity of a token but its relationships with other tokens.</p><p><strong>Token Limit</strong></p><p>The token limit is the maximum number of tokens that can be used in the prompt and the completion of the model. Most LLMs have token limits, which refer to the maximum number of tokens that the model can process at once. The token limit is determined by the architecture of the model</p><p><strong>Token processing cost</strong></p><p>Each token that the model processes requires computational resources — memory, processing power, and time. Thus, the more tokens a model has to process, the greater the computational cost</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uzg-xJDBgZd1p01hNGm0RQ.jpeg" /></figure><p><strong>Parameters</strong></p><p>We can think of parameters as internal settings or dials within a large language model that can be adjusted to optimize the process of taking tokens and generating new ones</p><p>When training a large language model, parameters are features of the LLM that are adjusted in order to optimize the model’s ability to predict the next token in a sequence</p><p>simplified explanation of how parameters are trained and function:</p><p>• A model’s parameters are set to an initial value, either randomly or based on previous training.</p><p>• The large language model being trained is fed vast amounts of textual data.</p><p>• As the model is trained, it takes the input and makes a prediction about what the correct output must be.</p><p>• In training, the LLM compares its prediction to the actual text to see if it predicted correctly or not. The model “learns” from its mistakes and adjusts its parameters if its prediction was incorrect.</p><p>• This process continues for millions or billions of examples, with the model adjusting its parameters each time and increasing its accuracy in prediction.</p><p>• Through this iterative process of prediction, error checking, and parameter adjustment, the LLM becomes more accurate and sophisticated in its language abilities.</p><p>LMs are complex systems with many different parameters. These parameters govern how the model learns and generates text. Some of the most important parameters for LLMs include:</p><p><strong>Model size</strong></p><p>The model size is the number of parameters in the LLM. The more parameters a model has, the more complex it is and the more data it can process. However, larger models are also more computationally expensive to train and deploy.</p><p><strong>Training data</strong></p><p>The training data is the dataset that the LLM is trained on. The quality and quantity of the training data has a significant impact on the performance of the model.</p><p><strong>Hyperparameters</strong></p><p>Hyperparameters are settings that control how the LLM is trained. These settings can be fine-tuned to improve the performance of the model on specific tasks.</p><p><strong>Parameter types</strong></p><p>1. float: 32-bit floating point, 4 bytes</p><p>2. half/BF16: 16-bit floating point, 2 bytes</p><p>3. int8: 8-bit integer, 1 byte</p><p>4. int4: 4-bit integer, 0.5 bytes</p><p>1 Billion Parameters = 4 x 10E9 bytes = 4GB</p><p>LLM has 70B parameters, it means that the model has 70 billion adjustable parameters. These parameters are used to learn the relationship between words and phrases in the training data. The more parameters a model has, the more complex it can be and the more data it can process. However, larger models are also more computationally expensive to train and deploy</p><p><strong>Is more parameters always better?</strong></p><p>The short answer is no.</p><p>A model with fewer parameters that is trained on high quality data will outperform a larger model trained on low quality data. In other words, the quality of the data used to train a model is just as important as the size of the model itself.</p><p><strong>Inference Memory Estimation</strong></p><p>For a 1 billion parameter model (1B), the estimated memory requirements are as follows:</p><p>— 4 GB for float precision, 2 GB for BF16 precision, and 1 GB for int8 precision. This estimation can be applied to other versions accordingly.</p><p><strong>Memory Required for Training</strong></p><p>A conservative estimate is about four times the memory needed for inference with the same parameter count and type. For example, training a 1B model with float precision would require approximately 16 GB (4 GB * 4).</p><p>· <strong>Gradients</strong></p><p>Memory required for gradients is equal to the number of parameters.</p><p>· <strong>Optimizer States</strong></p><p>The memory needed for the optimizer states depends on the type of optimizer used.</p><p>AdamW optimizer -twice the number of parameters, SGD optimizer -memory equivalent to the number of parameters is needed.</p><p><strong>Memory Usage with LoRA/QloRA Techniques</strong></p><p>LoRA involves running inference on the original model and training a smaller model to achieve nearly the same effect as training the original parameters.</p><p>For instance, if you need to fine-tune parameters of size 1024×512, using LoRA with a chosen Rank of 8, you only need to fine-tune the following number of parameters: 1024×8 + 512×8.</p><p>This process requires running inference on the original parameter volume once (without needing gradients and optimizer states), but it still requires some memory to store data during the computation. The total memory used is the sum of these requirements.</p><p><strong>Estimate Memory Usage for Inference</strong></p><p>1B-BF16 model would need memory equal to the number of parameters multiplied by the size of the type: 1 billion parameters * 2 bytes = 2 billion bytes.</p><p>2 billion bytes = 2 * 1,000 * 1,000 * 1,000 / 1024 / 1024 / 1024 ≈ 2 GB (considering 1000/1024)³ ≈ 0.93.</p><p><strong>Estimate Memory Usage for Training</strong></p><p>Back-propagation, Adam optimization, and Transformer architecture, the memory required for training is typically 3 to 4 times that needed for inference of an LLM of the same size. A conservative estimate is to calculate using a factor of 4</p><p>float type parameters: 1(billion parameters) * 4 (bytes per float parameter) * 4 = 16 GB</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=634963b36b59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different types of LLM Architectures]]></title>
            <link>https://medium.com/@plthiyagu/different-types-of-llm-architectures-bad6b8d57946?source=rss-b9ec6672f6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bad6b8d57946</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Thiyagarajan Palaniyappan]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 00:29:37 GMT</pubDate>
            <atom:updated>2024-04-09T00:29:37.924Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Encoder Only Models</strong></p><p>Encoder only models take an input sequence of text and produce a fixed-length vector representation that represents the meaning of the text.</p><p><strong>Pros</strong></p><p>· Effective in understanding text meaning</p><p>· Useful for downstream tasks like classification and sentiment analysis</p><p><strong>Cons</strong></p><p>· Cannot generate text, only understand text</p><p>· Requires fine-tuning for specific tasks</p><p>· May struggle with tasks requiring sequential generation</p><p><strong>Use Cases</strong></p><p>1. Text classification</p><p>2. Sentiment analysis</p><p>3. Sequence tagging</p><p><strong>Example</strong></p><p>1. BERT</p><p>2. ROBERTA</p><p>3. ViT</p><p><strong>Encoder-Decoder Models</strong></p><p>Encoder-Decoder models take an input sequence, generate an embedding using the encoder, and then produce an output sequence token by token using a process called autoregressive decoding.</p><p><strong>Pros</strong></p><p>· Suitable for tasks like machine translation and summarization</p><p>· Can generate text based on input sequence and context</p><p><strong>Cons</strong></p><p>· Complex to train and optimize</p><p>· Require larger computational resources</p><p><strong>Use Cases</strong></p><p>1. Machine translation</p><p>2. Summarization</p><p>3. Image captioning tasks</p><p><strong>Example</strong></p><p>1. T5</p><p>2. BART</p><p><strong>Decoder Only Models</strong></p><p>Decoder only models generate text in an autoregressive fashion, similar to encoder-decoder models, but without an encoder.</p><p><strong>Pros</strong></p><p>· Excellent at generating fluent text</p><p>· Easy to get started with, minimal fine-tuning required</p><p><strong>Cons</strong></p><p>· Lack control in the decoding process</p><p>· Possible to generate unintended results if not properly instructed</p><p>· Might lack bidirectional context understanding</p><p><strong>Use Cases</strong></p><p>1. Machine translation</p><p>2. Creative Writing</p><p>3. Question answering</p><p><strong>Example</strong></p><p>1. GPT</p><p>2. BLOOM</p><p>3. Falcon</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bad6b8d57946" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing LLM serving frameworks — LLMOps]]></title>
            <link>https://medium.com/@plthiyagu/comparing-llm-serving-frameworks-llmops-f02505864754?source=rss-b9ec6672f6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f02505864754</guid>
            <dc:creator><![CDATA[Thiyagarajan Palaniyappan]]></dc:creator>
            <pubDate>Sat, 16 Dec 2023 08:25:30 GMT</pubDate>
            <atom:updated>2023-12-16T08:25:30.532Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comparing LLM serving frameworks — LLMOps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*gCG3AUvvr35s4etkVQQaGA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*q7Ey_zfNeDvpLBYDugHjbQ.jpeg" /></figure><p><strong>Here are some key points to consider</strong></p><ol><li><strong>Triton Inference Server</strong> — powerful platform for deploying and scaling machine learning models in production environments. Setting up Triton Inference Server can be a complex process</li><li><strong>Text generation inference</strong> -Need native HuggingFace support and don’t plan to use multiple adapters for the core model.</li><li><strong>vLLM</strong> — Maximum speed is required for batched prompt delivery.</li><li><strong>DeepSpeed-MII</strong> — Have experience with the DeepSpeed library and wish to continue using it for deploying LLMs.</li><li><strong>OpenLLM</strong> — Want to connect adapters to the core model and utilize HuggingFace Agents, especially if you are not solely relying on PyTorch.</li><li><strong>MLC LLM</strong>- Want to natively deploy LLMs on the client-side (edge computing), for instance, on Android or iPhone platforms.</li><li><strong>Ray Serve</strong> -stable pipeline and flexible deployment. It is best suited for more mature projects.</li><li><strong>CTranslate2</strong> i-speed is important to you and if you plan to run inference on the CPU.</li></ol><p><strong>1. Triton Inference Server</strong></p><p>Triton enables teams to deploy any AI model from multiple deep learning and machine learning frameworks, including TensorRT, TensorFlow, PyTorch, ONNX, OpenVINO, Python, RAPIDS FIL, and more. Triton Inference Server supports inference across cloud, data center, edge and embedded devices on NVIDIA GPUs, x86 and ARM CPU, or AWS Inferentia</p><p><strong>Key Features of Triton</strong></p><ol><li>Support for various deep-learning (DL) frameworks</li><li>Simultaneous execution</li><li>Dynamic scheduling and batching</li><li>Backend extensibility</li><li>Model ensembles</li><li>Various metrics</li></ol><p><strong>2.Text Generation Inference</strong></p><p>Text Generation Inferenceis a Rust, Python, gRPC model server created by HuggingFace that can be used to host specific large language models. TGI suitable for deploy NLP based LLMS. Ex Falcon, LLAMa, T5,etc.,</p><p><strong>Key Features of TGI</strong></p><ol><li>Tensor Parallelism</li><li>Optimized Transformers Code</li><li>Quantization</li><li>Accelerated Weight Loading</li><li>Logits Warping</li><li>Custom Prompt Generation</li><li>Fine-tuning Support</li></ol><p><strong>3.vLLM: Versatile Large Language Model</strong></p><p>vLLM is a high-performance library designed for LLM inference and serving. It is known for its state-of-the-art serving throughput, efficient memory management using Paged Attention, and flexibility in serving various Hugging Face models</p><p><strong>Key Features of vLLM</strong></p><ol><li>High Throughput</li><li>Paged Attention</li><li>Continuous Batching</li><li>Optimized CUDA Kernels</li><li>Decoding Algorithms</li><li>Tensor Parallelism</li><li>Streaming Outputs</li></ol><p><strong>4.DeepSpeed MII</strong></p><p>The DeepSpeed Model Implementation for Inference (MII), aimed towards making low-latency, low-cost inference of powerful models not only feasible but also easily accessible</p><p><strong>Key Features of DeepSpeed MII</strong></p><ol><li>DeepFusion for Transformers</li><li>Multi-GPU Inference with Tensor-Slicing</li><li>INT8 Inference with ZeroQuant</li><li>ZeRO-Inference for Resource Constrained Systems</li><li>Compiler Optimizations</li></ol><p><strong>5.OpenLLM</strong></p><p>With OpenLLM, you can run inference on any open-source LLM, deploy them on the cloud or on-premises, and build powerful AI applications.</p><p><strong>Key Features of OpenLLM</strong></p><ol><li>State-of-the-art LLMs</li><li>Flexible APIs</li><li>Freedom to build</li><li>Streamline deployment</li><li>Bring your own LLM</li><li>Quantization</li><li>Streaming</li><li>Continuous batching</li></ol><p><strong>6. MLC LLM</strong></p><p><strong>M</strong>achine <strong>L</strong>earning <strong>C</strong>ompilation for <strong>L</strong>arge <strong>L</strong>anguage <strong>M</strong>odels (MLC LLM) is a high-performance universal deployment solution that allows native deployment of any large language models with wide range of hardware backends, including CPUs and GPUs and native applications</p><p><strong>Key Features of MLC LLM</strong></p><ol><li>Universal deployment</li><li>Platform-native runtimes</li><li>Memory optimization</li></ol><p><strong>7. Ray Serve</strong></p><p>Ray Serve is a scalable model-serving library for building online inference APIs. Serve is framework-agnostic, so you can use a single toolkit to serve everything from deep learning models.</p><p><strong>Key Features of Ray Serve</strong></p><ol><li>Batch Inference</li><li>Many Model Training</li><li>Autoscale across multiple replicas</li><li>Monitoring dashboard and Prometheus metrics</li></ol><p><strong>8. CTranslate2</strong></p><p>CTranslate2 is a C++ and Python library for efficient inference with Transformer models.</p><p><strong>Key Features o CTranslate2</strong></p><ol><li>Fast and efficient execution on CPU and GPU</li><li>Dynamic memory usage</li><li>Multiple CPU architectures support</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f02505864754" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calculate GPU Requirements for Your LLM Training]]></title>
            <link>https://medium.com/@plthiyagu/calculate-gpu-requirements-for-your-llm-training-7122a3700547?source=rss-b9ec6672f6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7122a3700547</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <dc:creator><![CDATA[Thiyagarajan Palaniyappan]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 00:32:05 GMT</pubDate>
            <atom:updated>2023-12-06T00:32:05.268Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Graphics Processing Unit (GPU)</strong></p><p>GPUs are a cornerstone of LLM training due to their ability to accelerate parallel computations. Modern deep learning frameworks, such as TensorFlow and PyTorch, leverage GPUs to perform matrix multiplications and other operations required for neural network training. When selecting a GPU, factors like memory capacity (VRAM), memory bandwidth, and processing power (measured in CUDA cores) are crucial. High-end GPUs like NVIDIA’s Tesla series or the GeForce RTX series are commonly favored for LLM training. The more powerful the GPU, the faster the training process.</p><h3>Data Center GPU Options</h3><p>The following are some of the world’s most powerful, data center grade GPUs, commonly used to build large-scale GPU infrastructure.</p><h4>NVIDIA Tesla A100</h4><p>The A100 is based on Tensor Cores and leverages multi-instance GPU (MIG) technology. It is built for workloads such as high-performance computing (HPC), machine learning and data analytics.</p><p>Tesla A100 is intended for scalability (up to thousands of units) and can be separated into seven GPU instances for different workload sizes. The A100 offers performance reaching up to 624 teraflops (billion floating-point operations per second) and has 40GB memory, 1,555 GB bandwidth and 600GB/s interconnects.</p><h4>NVIDIA Tesla V100</h4><p>The V100 GPU is also based on Tensor Cores and is designed for applications such as machine learning, deep learning and HPC. It uses NVIDIA Volta technology to accelerate common tensor operations in deep learning workloads. The Tesla V100 offers performance reaching 149 teraflops as well as 32GB memory and a 4,096-bit memory bus.</p><h4>NVIDIA Tesla P100</h4><p>The Tesla P100 GPU is based on an NVIDIA Pascal architecture designed specifically for HPC and machine learning. P100 offers performance of up to 21 teraflops, with 16GB of memory and a 4,096-bit memory bus.</p><h4>NVIDIA Tesla K80</h4><p>The K80 GPU uses NVIDIA Kepler architecture, which enables the accelerating of data analytics and scientific computing. It incorporates GPU Boost™ technology and 4,992 NVIDIA CUDA cores. Tesla K80 offers up to 8.73 teraflops performance, with 480GB memory bandwidth and 24GB of GDDR5 memory.</p><h4>Google TPU</h4><p>Google offers slightly different tensor processing units (TPUs), which are application-specific integrated circuits (ASICs) based on chips or the cloud, that support deep learning. These TPUs are designed specifically to be used with TensorFlow and can only be found on the Google Cloud Platform.</p><p>Google TPUs offer performance of up to 420 teraflops with a high bandwidth memory (HBM) of 128 GB. You can also find pod versions that offer performance of over 100 petaflops with 32TB HBM and 2D toroidal mesh networks.</p><p>Commodity GPUs only have 16 GB / 24 GB GPU memory, and even the most advanced NVIDIA A100 and V100 GPUs only have 40 GB / 80 GB of GPU memory per device.</p><p><strong>How to calculate no of A100 GPU needed for LLM Training?</strong></p><ol><li>No of token in billions</li><li>Hour to finish training</li><li>Enter model size in GB</li><li>No of epochs</li></ol><p><strong>Number of A100 (80G) GPUs needed for Training</strong>= ((tokens * epochs * model_size * 13.3) / hours)</p><p><strong>How to calculate no of A100 GPU needed for LLM Inference?</strong></p><ol><li>Model throughput (in tokens/sec)</li><li>Max number queries per minute</li><li>Average number of output tokens</li></ol><p><strong>Number of A100 (80G) GPUs needed for Inference</strong>= (output_tokens / throughput * qpm / 60)</p><h3>Model Memory Calculator</h3><p>This tool will help you calculate how much vRAM is needed to train and perform big model inference on a model hosted on the 🤗 Hugging Face Hub.</p><p><a href="https://huggingface.co/docs/accelerate/main/en/usage_guides/model_size_estimator">https://huggingface.co/docs/accelerate/main/en/usage_guides/model_size_estimator</a></p><h3>Different GPU performance comparison</h3><ol><li><a href="https://developer.nvidia.com/hpc-application-performance">https://developer.nvidia.com/hpc-application-performance</a></li><li><a href="https://lambdalabs.com/gpu-benchmarks">https://lambdalabs.com/gpu-benchmarks</a></li><li><a href="https://huggingface.co/docs/transformers/perf_train_gpu_one#anatomy-of-models-memory">https://huggingface.co/docs/transformers/perf_train_gpu_one#anatomy-of-models-memory</a></li></ol><h3>Best Practices for Effective Distributed LLM Training</h3><p>Here are the best practices for implementing effective distributed systems in <a href="https://www.appypie.com/blog/large-language-models-training"><strong>LLM training</strong></a>:</p><p>1. <strong>Choose the Right Framework:</strong> Utilize frameworks designed for distributed training, such as TensorFlow or PyTorch. These frameworks provide tools and APIs that simplify the implementation of distributed training strategies.</p><p>2. <strong>Optimize Communication:</strong> Minimize communication overhead by using techniques like gradient accumulation before updating the model or using techniques like gradient compression to reduce the amount of data exchanged between nodes.</p><p>3. <strong>Experiment with Batch Sizes:</strong> Finding the optimal batch size for distributed training is crucial. Too small a batch size might lead to increased communication overhead, while too large a batch size can cause memory constraints.</p><p>4. <strong>Monitor and Tune:</strong> Regularly monitor the performance of your distributed training setup. Adjust hyperparameters, partitioning strategies, and communication settings to optimize performance.</p><p>5. <strong>Backup and Recovery:</strong> Implement mechanisms for regular model checkpoints and efficient recovery in case of failures. This ensures that training can be resumed without starting from scratch.</p><h3>Challenges of Distributed LLM Training</h3><p>While distributed systems offer significant advantages for speeding up LLM training, they also introduce challenges that must be addressed:</p><ul><li><strong>Communication Overhead:</strong> In distributed systems, communication between nodes becomes a potential bottleneck. When aggregating gradients or exchanging model updates, the time spent on communication can impact the overall speedup.</li><li><strong>Synchronization Complexity:</strong> Coordinating the updates from multiple machines can be complex, especially in model parallelism scenarios. Ensuring that different parts of the model are synchronized correctly requires careful design.</li><li><strong>Failure Handling:</strong> Distributed systems introduce the possibility of individual nodes failing. Robust mechanisms for handling failures and resuming training are essential to maintain progress.</li><li><strong>Resource Management:</strong> Efficiently managing resources across multiple machines, including CPUs and GPUs, requires sophisticated resource allocation and scheduling strategies.</li></ul><p><strong>References</strong></p><ol><li><a href="https://docs.nvidia.com/deeplearning/performance/dl-performance-gpu-background/index.html">https://docs.nvidia.com/deeplearning/performance/dl-performance-gpu-background/index.html</a></li><li><a href="https://medium.com/@dzmitrybahdanau/the-flops-calculus-of-language-model-training-3b19c1f025e4">https://medium.com/@dzmitrybahdanau/the-flops-calculus-of-language-model-training-3b19c1f025e4</a></li><li><a href="https://huggingface.co/docs/accelerate/main/en/concept_guides/training_tpu">https://huggingface.co/docs/accelerate/main/en/concept_guides/training_tpu</a></li><li><a href="https://towardsdatascience.com/how-to-build-a-multi-gpu-system-for-deep-learning-in-2023-e5bbb905d935">https://towardsdatascience.com/how-to-build-a-multi-gpu-system-for-deep-learning-in-2023-e5bbb905d935</a></li><li><a href="https://blog.eleuther.ai/transformer-math/">https://blog.eleuther.ai/transformer-math/</a></li><li><a href="https://timdettmers.com/2023/01/30/which-gpu-for-deep-learning/#When_do_I_need_11_GB_of_Memory">https://timdettmers.com/2023/01/30/which-gpu-for-deep-learning/#When_do_I_need_11_GB_of_Memory</a></li><li><a href="https://lambdalabs.com/gpu-benchmarks">https://lambdalabs.com/gpu-benchmarks</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7122a3700547" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>