<?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 Subhasmukherjee on Medium]]></title>
        <description><![CDATA[Stories by Subhasmukherjee on Medium]]></description>
        <link>https://medium.com/@23subhasmukherjee?source=rss-34a20cdf5e7d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JlHS_nR2HLmO54G2</url>
            <title>Stories by Subhasmukherjee on Medium</title>
            <link>https://medium.com/@23subhasmukherjee?source=rss-34a20cdf5e7d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:26:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@23subhasmukherjee/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[How Vector Databases became the brain of the AI systems]]></title>
            <link>https://medium.com/@23subhasmukherjee/how-vector-databases-became-the-brain-of-the-ai-systems-97f80ec61f17?source=rss-34a20cdf5e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/97f80ec61f17</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Subhasmukherjee]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 11:35:45 GMT</pubDate>
            <atom:updated>2025-10-28T11:35:45.224Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Artificial Intelligence has made a tremendous impact in the last few years which evolved from single pattern recognition to complex reasoning and even content generation. But have you ever wondered what is behind these high functioning AI system architecture — it is the <strong>Vector Database</strong>. <br>If one says AI is the “brain”, then VectorDB would be the “memory”, enabling AI to understand context, review past interactions and understand intent of prompts.</blockquote><p>In this blog, we will explore different VectorDB like <strong>Pinecone, FAISS</strong> and <strong>Chroma</strong>, why they are indispensable for AI startups, and how they power the future of semantic search and intelligent memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pgo9oaDR8wwnGSrf" /></figure><h3>Understanding Vector Databases</h3><p>Traditional databases store structured data into rows, columns and clearly defined relationships. This works great for transactional data, but AI deals with <strong>unstructured, high dimensional data</strong> — images, texts, audio and embeddings generated by machine learning models.</p><p>A vector database stores vectors which are numerical representation of data in multi dimensional space. For example :</p><ol><li>A sentence like ‘AI is transforming healthcare’ can be transformed in to a 512-dimensional embedding vector.</li><li>An image of a cat can be transformed in to a vector capturing features.</li></ol><p>These vectors helps the AI to perform semantic searches to find similar matches rather than only exact matches. This capability is used in powerful chatbots, recommendation system and AI modules.</p><h3>Popular Names you may have heard in the VectorDB space</h3><h4><strong>Pinecone</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*N-l20J9pJtNWb5hD.png" /></figure><p>Pinecone is a fully managed AI Vector database designed for real time AI applications. The key strengths include :</p><ol><li><em>Scalability</em> : Handling billions of vectors with low latency.</li><li><em>Real time indexing</em> : Updates vectors instantly for dynamic applications.</li><li><em>Integration with AI models</em> : It works seamlessly with OpenAI embeddings, Hugging Face Transformers and many other AI frameworks.</li></ol><h3>Step-by-Step Guide: Using Pinecone</h3><p>Step 1: Install the SDK</p><p>In your Python environment:</p><pre>pip install pinecone-client openai</pre><p>Step 2: Get Your API Key</p><ul><li>Go to <a href="https://www.pinecone.io/">https://www.pinecone.io</a></li><li>Create a free account</li><li>From your dashboard, copy your <strong>Pinecone API key</strong> and <strong>Environment</strong> (region)</li></ul><p>Step 3: Initialise Pinecone in Your Code</p><pre>import pinecone</pre><pre># Initialise connection<br>pinecone.init(<br>    api_key=&quot;YOUR_PINECONE_API_KEY&quot;,<br>    environment=&quot;YOUR_PINECONE_ENVIRONMENT&quot;<br>)</pre><p>Step 4: Create an Index</p><p>An <strong>index</strong> is where your vector data will be stored.<br> For example, let’s create an index called semantic-search with 1536 dimensions (the output size of OpenAI text embeddings):</p><pre>index_name = &quot;semantic-search&quot;</pre><pre># Create index (only once)<br>if index_name not in pinecone.list_indexes():<br>    pinecone.create_index(name=index_name, dimension=1536, metric=&quot;cosine&quot;)</pre><p>Step 5: Connect to the Index</p><pre>index = pinecone.Index(index_name)</pre><p>Step 6: Generate and Upsert Embeddings</p><p>Let’s use OpenAI’s text-embedding model to generate vectors and store them in Pinecone.</p><pre>from openai import OpenAI<br>client = OpenAI(api_key=&quot;YOUR_OPENAI_KEY&quot;)</pre><pre># Example texts<br>texts = [<br>    &quot;Machine learning improves with data.&quot;,<br>    &quot;Neural networks mimic the human brain.&quot;,<br>    &quot;Pinecone enables fast vector search.&quot;<br>]</pre><pre># Generate embeddings<br>embeddings = [<br>    client.embeddings.create(<br>        model=&quot;text-embedding-3-small&quot;,<br>        input=text<br>    ).data[0].embedding<br>    for text in texts<br>]</pre><pre># Upsert (upload) to Pinecone<br>vectors = [(f&quot;id-{i}&quot;, embeddings[i], {&quot;text&quot;: texts[i]}) for i in range(len(texts))]<br>index.upsert(vectors=vectors)</pre><p>Step 7: Query the Database</p><p>Now, you can search semantically!<br> Example: find sentences similar to <em>“AI systems use vector search.”</em></p><pre>query = &quot;AI systems use vector search.&quot;</pre><pre># Get embedding for the query<br>query_emb = client.embeddings.create(<br>    model=&quot;text-embedding-3-small&quot;,<br>    input=query<br>).data[0].embedding</pre><pre># Query Pinecone<br>result = index.query(vector=query_emb, top_k=3, include_metadata=True)<br>print(result)</pre><p>You’ll get the top semantically similar results, even if they don’t share exact words.</p><p>Step 8: Delete Index (Optional)</p><p>When done testing:</p><pre>pinecone.delete_index(index_name)</pre><h3><strong>Use case</strong></h3><p>Let us imagine a Customer Support AI that remembers past interactions. The role of Pinecone here is that it allows the system to instantly retrieve previous interactions semantically, so that the AI bot can provide context aware answers.</p><h4>FAISS (Facebook AI Similarity Search)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IZLgNGx-AQTVcGHE.jpeg" /></figure><p>FAISS is an open source library developed by Facebook AI Research for efficient similarity search and clustering of dense vectors.</p><ol><li><em>Speed Optimisation</em> : Supports GPU acceleration for massive datasets.</li><li><em>Highly flexible</em> : It offers various indexing strategies like IVF, Flat and PQ.</li><li><em>Great for Research and Prototyping</em> : Because FAISS is open source, AI teams can experiment and contribute freely.</li></ol><h3>Step-by-Step Guide: Using FAISS in Python</h3><p>Step 1: Install Dependencies</p><p>Install FAISS and an embedding model (e.g., Sentence Transformers):</p><pre>pip install faiss-cpu sentence-transformers</pre><p><em>(Use </em><em>faiss-gpu if you have a CUDA-compatible GPU.)</em></p><p>Step 2: Import Required Libraries</p><pre>import faiss<br>import numpy as np<br>from sentence_transformers import SentenceTransformer</pre><p>Step 3: Load an Embedding Model</p><p>We’ll use a pretrained model to convert text into embeddings (vectors).</p><pre>model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)</pre><p>Step 4: Prepare Your Data</p><p>Let’s create a few example sentences.</p><pre>sentences = [<br>    &quot;Machine learning improves with more data.&quot;,<br>    &quot;Neural networks mimic how the human brain works.&quot;,<br>    &quot;FAISS enables fast similarity search.&quot;,<br>    &quot;Vector databases store embeddings for AI applications.&quot;<br>]</pre><p>Step 5: Generate Embeddings</p><pre>embeddings = model.encode(sentences)<br>print(&quot;Embedding shape:&quot;, embeddings.shape)</pre><p>Output example:</p><pre>Embedding shape: (4, 384)</pre><p>So, we have 4 sentences, each represented by a 384-dimensional vector.</p><p>Step 6: Create a FAISS Index</p><p>We’ll create a <strong>FlatL2 index</strong> — the simplest and most accurate index type (it computes Euclidean distance).</p><pre>dimension = embeddings.shape[1]  # 384<br>index = faiss.IndexFlatL2(dimension)</pre><p>For <strong>cosine similarity</strong>, you can normalize your vectors first:</p><pre>faiss.normalize_L2(embeddings)</pre><p>Step 7: Add Vectors to the Index</p><pre>index.add(embeddings)<br>print(&quot;Total vectors indexed:&quot;, index.ntotal)</pre><p>Step 8: Query the Index</p><p>Now let’s find sentences similar to a query.</p><pre>query = &quot;AI systems use vector search.&quot;<br>query_vector = model.encode([query])<br>faiss.normalize_L2(query_vector)</pre><pre># Search top 3 similar sentences<br>k = 3<br>distances, indices = index.search(query_vector, k)</pre><p>Step 9: Display Results</p><pre>print(&quot;Query:&quot;, query)<br>print(&quot;\nTop Matches:&quot;)<br>for i, idx in enumerate(indices[0]):<br>    print(f&quot;{i+1}. {sentences[idx]} (Score: {distances[0][i]:.4f})&quot;)</pre><p><strong>Output Example:</strong></p><pre>Query: AI systems use vector search.</pre><pre>Top Matches:<br>1. FAISS enables fast similarity search. (Score: 0.1537)<br>2. Vector databases store embeddings for AI applications. (Score: 0.1824)<br>3. Neural networks mimic how the human brain works. (Score: 0.3042)</pre><p>Step 10: (Optional) Save and Load Index</p><p>To save your FAISS index:</p><pre>faiss.write_index(index, &quot;faiss_index.idx&quot;)</pre><p>To load it again later:</p><pre>index = faiss.read_index(&quot;faiss_index.idx&quot;)</pre><h3>Use case</h3><p>Recommendation engines at scale. For example : Netflix-Style movie suggestions — FAISS can quickly find movies or TV shows with similar semantic relationships based on the vector embedding or descriptions or user preferences.</p><h3>Chroma</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/0*8DlHmUr7PWiI8iFW.png" /></figure><p>Chroma is an emerging vector database focused on AI-first applications. It is designed for ease of use especially in Retrieval Augmented Generation (RAG) systems</p><ul><li><strong>RAG integration:</strong> Combines generative AI with vector-based retrieval for smarter, knowledge-grounded outputs.</li><li><strong>Python-friendly:</strong> It provides a Simple API for Python developers.</li><li><strong>Open-source with enterprise support:</strong> Ideal for startups that need flexibility without vendor lock-in.</li></ul><h3>Step-by-Step Guide: Using Chroma in Python</h3><p>Step 1: Install Chroma</p><pre>pip install chromadb sentence-transformers</pre><p>Step 2: Import and Initialise Client</p><pre>import chromadb<br>from sentence_transformers import SentenceTransformer</pre><pre># Initialise Chroma client<br>client = chromadb.Client()</pre><p>If you want persistence (data saved across runs):</p><pre>client = chromadb.PersistentClient(path=&quot;./chroma_db&quot;)</pre><p>Step 3: Create or Get a Collection</p><p>A <strong>collection</strong> in Chroma is like a “table” where you’ll store embeddings.</p><pre>collection = client.get_or_create_collection(name=&quot;semantic_search&quot;)</pre><p>Step 4: Load an Embedding Model</p><p>Use any embedding model — for simplicity, we’ll use a SentenceTransformer.</p><pre>model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)</pre><p>Step 5: Prepare Your Data</p><pre>texts = [<br>    &quot;Artificial Intelligence is transforming industries.&quot;,<br>    &quot;Machine learning improves performance with data.&quot;,<br>    &quot;Chroma is an open-source vector database.&quot;,<br>    &quot;Vector embeddings power semantic search.&quot;<br>]</pre><p>Step 6: Generate and Add Embeddings</p><pre>embeddings = model.encode(texts).tolist()</pre><pre>collection.add(<br>    ids=[f&quot;doc_{i}&quot; for i in range(len(texts))],<br>    documents=texts,<br>    embeddings=embeddings<br>)</pre><p>Now your data is stored in Chroma as vectors with metadata.</p><p>Step 7: Query the Database (Semantic Search)</p><p>Let’s find the most similar sentences to a query.</p><pre>query = &quot;AI systems use semantic understanding.&quot;<br>query_emb = model.encode([query]).tolist()</pre><pre>results = collection.query(<br>    query_embeddings=query_emb,<br>    n_results=3,<br>    include=[&quot;documents&quot;, &quot;distances&quot;]<br>)</pre><pre>for doc, dist in zip(results[&quot;documents&quot;][0], results[&quot;distances&quot;][0]):<br>    print(f&quot;Result: {doc} (Score: {dist:.4f})&quot;)</pre><p>You’ll get the top 3 semantically similar sentences — not just keyword matches.</p><p>Step 8: Update or Delete Entries</p><p>You can modify your database dynamically.</p><p><strong>Update example:</strong></p><pre>collection.update(<br>    ids=[&quot;doc_2&quot;],<br>    documents=[&quot;Chroma is a Python-first vector database for AI memory.&quot;]<br>)</pre><p><strong>Delete example:</strong></p><pre>collection.delete(ids=[&quot;doc_3&quot;])</pre><p>Step 9: Persist and Reload Data</p><p>Chroma automatically stores data if you use PersistentClient.<br> When you restart your app:</p><pre>client = chromadb.PersistentClient(path=&quot;./chroma_db&quot;)<br>collection = client.get_collection(&quot;semantic_search&quot;)</pre><p>Your vectors are still available!</p><p><strong>Use case:</strong> AI writing assistants. Chroma can store large corpora of documents as embeddings. When a user asks a question, the AI retrieves the most relevant documents and uses them to generate accurate answers.</p><h3>Why every AI startup needs Vector Databases</h3><ol><li><strong>Memory for AI systems </strong><br>Generative AI models like GPT and Claude can only remember limited context. Vector database helps by storing external knowledge, effectively acting as long term memory.</li><li><strong>Semantic Search </strong><br>The old system of keyboard search is primitive. Semantic search retrieves results based on the underlying meaning, not literal matches but based on a scoring factor which allows complex chatbots, recommendation systems and knowledge engines to put together a huge strata of outputs.</li><li><strong>Scalability</strong><br>Probably the most important factor as to why one should use VectorDB. AI applications often need to handle millions of vectors. Managed Vector Databases like Pinecone scales effortlessly, saving the time of startups and infrastructure facility.</li><li><strong>Enhanced Personalisation </strong><br>Vector database as they are not bound to strict exact matches lets the AI to retrieve and reason over user-specific embeddings. This means that the AI assistant will remember preferences, prior conversations and behaviour giving users a personal experience.</li></ol><h3>What could be the Real World Applications</h3><ol><li><strong>AI-powered Customer Support </strong><br>Imagine a customer returning to a chat with your AI assistant. Instead of starting from scratch, the bot recalls previous conversations — the issue which is been discussed, the preferences being noted and even the tone of previous responses. <br>This “<strong>memory</strong>” is made possible by vector databases like Pinecone or Chroma which store and retrieve embeddings of past chats. When a new query comes in, the AI searches semantically for related history and context aware reply.</li><li><strong>Knowledge Retrieval Systems</strong></li></ol><p>AI research assistants and enterprise knowledge bots use vector databases to store massive corpora of documents, papers, and FAQs as embeddings.<br> When a user asks a question, instead of matching keywords, the AI finds semantically similar text snippets. This allows it to retrieve <em>conceptually relevant</em> information — even if the wording is different.<br> <em>Example:</em> A medical research assistant retrieving relevant clinical studies when asked, “What are recent advances in <strong>Alzheimer’s biomarkers</strong>?”</p><p><strong>3. AI Content Generation (RAG Systems)</strong></p><p><strong>Retrieval-Augmented Generation (RAG)</strong> systems use vector databases to ground generative AI outputs in factual data. Before generating a response, the AI queries the vector database for relevant context and uses that to produce accurate, source-backed text.<br> This combination prevents hallucinations and ensures domain relevance.<br> <em>Example:</em> AI-powered writing tools like <strong>Perplexity AI</strong> or <strong>ChatGPT</strong> with retrieval plugins, which pull verified content from databases before generating answers.</p><h3>Conclusion</h3><p>Vector databases have become the unsung heroes of AI, powering the memory and intelligence behind every new and modern applications. From Pinecone’s managed scalability and FAISS faster similarity search, these tools are very important for emerging startups and blue chip companies to adapt to intelligent, context-aware AI products.</p><p>In this era of booming AI, a startup without a vector database is like a brain without memory. Semantic Searching, RAG systems and context awareness are not just fancy nice-to-haves, they are essential and are at table stake.</p><p>If you yourself are building an AI product today, and vector database is not in your priority list, you are missing out on the core tech that could make your agent truly intelligent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97f80ec61f17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explainable AI (xAI): How SHAP and LIME demystify AI decisions.]]></title>
            <link>https://medium.com/@23subhasmukherjee/explainable-ai-xai-how-shap-and-lime-demystify-ai-decisions-5b1fb3a72818?source=rss-34a20cdf5e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b1fb3a72818</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Subhasmukherjee]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 07:30:15 GMT</pubDate>
            <atom:updated>2025-09-18T07:30:15.714Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>As <strong>Artificial Intelligence</strong> models grow more complex — from deep neural networks to gradient boosting trees — their predictive power is often matches only by their opacity. These are called “<strong><em>black-box</em></strong>” models where one can see the inputs and the outputs, but the internal decision making system remains a mystery. If a model is predicting to deny a loan, a fraud transaction or diagnose a disease, <em>we must be able to ask — Why ?</em></blockquote><p>The field of <strong>Explainable AI (xAI)</strong> has emerged to answer this question. Among the most powerful and well-known methods of this type are <strong>SHAP</strong> and <strong>LIME</strong> scores. They do not change the model; rather act as interpreters, translating the model’s complex topic in to human-understandable works. Lets move on to understand what they are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*538KJsMPKCoWubdlVLeLoQ.png" /></figure><h3><strong>LIME : The Local Interpreter</strong></h3><p><strong>What is it ?<br></strong>Instead of trying to explain the whole complex model all at once(global explanation), <strong>LIME</strong> focuses on explaining a single prediction (local explanation). It’s main propaganda is : No matter how complex a model really is, it can be easily explained by a simple interpretable model (linear regression) <em>in the vicinity of that instance.</em></p><p><strong>How it works ? The three-step process :</strong></p><p>Imagine a model trying to predict whether a patient has heart disease or not based on not less than 100 of features. Suppose we want to know why it predicted “Yes” for a specific patient.</p><ol><li>Perturbation : It creates a new dataset by slightly perturbing (adding small changes to the patient data). It might create some “synthetic” patient data copying the blood pressure, cholesterol level etc. Some data may be different while others not so much.</li><li>Prediction : It fits the new dataset into the original black box model for prediction. (Yes/No, or probability scores).</li><li>Interpretable Model Fitting : LIME now has a simple dataset with its perturbed data and their black box model predictions. LIME now fits a simple linear models with Lasso Regulariation on the new dataset.</li></ol><p>The result is a linear explanation that might look like this:</p><ul><li>High Cholesterol (+0.35)</li><li>Age &gt; 60 (+0.28)</li><li>Low HDL (-0.15)</li></ul><p>The coefficients of this simple model helps us understand which features are responsible for this particular prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*ivrHos4XH4j3yQqXIp7I8w.png" /></figure><h4>Analogy :</h4><p>Think of trying to understand a complex curved surface (black box model). LIME does not explain the whole surface. Instead it presses a small , flat piece of glass against one single point on the curved surface. The glass shows the slope of the curve at that point which is a good enough local approximation.</p><h4>Strengths:</h4><ol><li><em>Model Agnostic</em> : Works with any black box ( image, text, etc..)</li><li><em>Intuitive : </em>Concept of local approximation is easy to grasp</li><li><em>Flexible :</em> Can be adapted to different data types and models</li></ol><h4>Weakness :</h4><ol><li><em>Easily Played :</em> Research has shown that it is easy to create models that LIME explains well but are actually misleading.</li><li><em>Instability :</em> Perturbation is random meaning if LIME is performed two times, then same instance can yeild slightly different results.</li></ol><h3>2. SHAP — The Game Theorist</h3><p><strong>What is it ?</strong></p><p>SHAP (SHapley Additive exPlanations) takes a fundamentally different approach rooted in co operative game theory from 1950s. The main logic behind the game theory is : How can i fairly distribute the “payout” (predictions) among the “players”(or the input features)?</p><blockquote>SHAP values provide a unified measure of feature importance that is both theoretically rigorous and locally accurate.</blockquote><p><strong>How it works ? The Shapley Value</strong></p><p>The Shapley value calculates the marginal contribution of a features value with the combinations of all the other features.</p><p>Let’s use the loan application example. The model predicts a $100,000 loan amount. The features are Income, Credit Score, and Age. How much of that $100k should we attribute to Credit Score being 750?</p><ol><li><strong>Form Coalitions </strong>: SHAP considers every possible combination of features that can be used.</li></ol><ul><li>No features (a baseline average prediction)</li><li>Just Income</li><li>Just Credit Score</li><li>Just Age</li><li>Income + Credit Score</li><li>Income + Age</li><li>Credit Score + Age</li><li>All three features</li></ul><p>2. <strong>Calculate Marginal Contribution</strong> : For each coalition, it asks: “How much does the prediction <em>change</em> when we add Credit Score=750 to this specific group?&quot; For example, the prediction with just Income might be $80k. Adding Credit Score=750 pushes it to $95k. The marginal contribution for that specific coalition is +$15k.</p><p>3. <strong>Average Fairly </strong>: The Shapley value is the weighted average of all these possible contributions across all coalitions. This ensures that every combination gets a fair distribution of credit only for the additive effect it has for the context of the features present</p><p>The final explanation is additive. It starts from a base value (the average model prediction) and adds/subtracts the Shapley values for each feature to arrive at the actual prediction:<br>Prediction = Base Value + SHAP(Income) + SHAP(Credit Score) + SHAP(Age)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*17laZNTHtfWt5OmfjQGcMA.png" /></figure><h4>Analogy :</h4><p>Imagine a Group Project where the grade is an A. The Shapley value would clearly determine which member contributed how much in the project, based on the contributions of different combinations of sub groups and how each member has worked.</p><h4>Strengths:</h4><ul><li>Theoretically Sound: Rooted in a robust mathematical framework with desirable properties (e.g., fairness, consistency).</li><li>Global and Local: While explaining single predictions, you can aggregate many <strong>SHAP</strong> values to get a consistent global view of feature importance.</li><li>Consistent Explanations: Unlike <strong>LIME</strong>, the explanation is deterministic for a given model and instance.</li></ul><h4>Weaknesses:</h4><ul><li>Computationally Expensive: Calculating exact Shapley values requires evaluating all 2^M possible coalitions (where M is the number of features), which is intractable for high-dimensional data. In practice, clever approximations (like <strong>KernelSHAP</strong> or <strong>TreeSHAP</strong>) are used.</li><li>Can be Misinterpreted: The “base value” is the average model output, not necessarily a “neutral” value in a human sense. SHAP explains deviation from the average, not from zero.</li></ul><h4>Conclusion : Choosing the right tool kit</h4><p>Both <strong>SHAP</strong> and <strong>LIME</strong> are invaluable in the XAI toolkit. The choice between them depends on your goal :</p><ul><li>Use <strong>LIME</strong> when you need a fast, intuitive explanation for a specific decision and want to stay model agnostic. Its easy for quick debugging and building initial trust.</li><li>Use <strong>SHAP</strong> when you need a more rigorous, precise and mathematical explanation of the prediction. It is the preferred choice for in-depth model analysis, auditing and when you explicitely want to compare feature importance across entire dataset.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b1fb3a72818" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Varieties of RAG Chunking Techniques: A Comprehensive Analysis of Strategies for Downstream Task…]]></title>
            <link>https://blog.gopenai.com/varieties-of-rag-chunking-techniques-a-comprehensive-analysis-of-strategies-for-downstream-task-54508fa87d3f?source=rss-34a20cdf5e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/54508fa87d3f</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Subhasmukherjee]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 11:48:51 GMT</pubDate>
            <atom:updated>2025-08-19T12:03:54.841Z</atom:updated>
            <content:encoded><![CDATA[<h3>Varieties of RAG Chunking Techniques: A Comprehensive Analysis of Strategies for Downstream Task Optimisation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*3JdZr4Y6xFAS1WiBxwoN7A.png" /><figcaption>Illustration of the RAG (Retrieval-Augmented Generation) architecture workflow, highlighting how prompts are passed to a retriever to fetch relevant chunks from multiple documents across various chunking strategies.</figcaption></figure><p>A few months ago, I was working on a legal document search engine. Every time I fed long documents in to my <strong>Retrieval Augmented Generation(RAG)</strong> framework it would hallucinate, forgot key points or just get lost in the structure. The issue ? My poor chunking strategies which was constantly splitting text arbitrarily — sometimes even breaking sentences from random parts making the model confused which generates irrelevant responses.</p><p>After much frustration, I realised: <strong>chunking based on complete sentences</strong> — not raw tokens — preserved meaning and made the models’ responses drastically better. That’s when I began exploring <strong>sentence-based chunking</strong> seriously.</p><h3>What we’re gonna learn from this blog :</h3><ol><li>Understand the <strong>importance of chunking strategies</strong> in Retrieval Augmented Generation(RAG).</li><li>Deep-dive in to <strong>distinct chunking</strong> strategies.</li><li>Gets hands-on<strong> mathematical intuitions</strong> and <strong>formulas </strong>behind each strategy.</li><li>Learn <strong>when</strong> and <strong>why</strong> to use a particular chunking method based on the desired workflow.</li><li>See how different chunking techniques affect <strong>retrieval quality</strong>, <strong>response relevance</strong>, and <strong>LLM performance</strong>.</li></ol><h4>Abstract :</h4><p>Retrieval Augmented Generation(RAG) relies heavily on proper chunking for relevant <strong>information retrieval </strong>and<strong> generation</strong>. In this blog, we will deep dive in to 9 distinct chunking strategies: how they work along with their <strong>mathematical formulas</strong>, implementation and task-specific work.</p><p>We categorise these strategies based on their <strong>semantic coherence</strong> and <strong>structure awareness</strong> which gives a clear idea about the practical implementation guidance for each approach.</p><h4>What exactly is Chunking in RAG ?</h4><p>Document Chunking represents a fundamental preprocessing step in the Retrieval Augmented Generation(RAG) framework. The choice of chunking strategy significantly impacts different downstream tasks like <strong>Question-Answering, Summarisation and Knowledge Extraction.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e32V-KUiM_fpteIZFlB4kA.png" /><figcaption>A visual breakdown of key chunking strategies used to enhance Retrieval-Augmented Generation (RAG) performance.</figcaption></figure><h3>2. Mathematical Framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBLyFOYk5kgnE2noyntjcA.jpeg" /></figure><h3>3. Chunking Methodologies :</h3><h4>3.1. Sentence Based Chunking :</h4><p><strong>What is it? :</strong></p><p>Sentence Based Chunking is one of the earliest chunking strategies. It treats a sentence as a whole for chunking without any fixed token length or structure. Sentences are grouped sequentially together until a pre-defined token limit is reached.</p><p><strong>When to use :</strong></p><ul><li><strong><em>Question Answering</em></strong>: Optimal for factual QA where answers span single sentences</li><li><strong><em>Citation Systems</em></strong><em>:</em> Maintains precise source attribution</li><li><strong><em>Legal Document Analysis</em></strong><em>:</em> Preserves clause-level granularity.</li></ul><p><strong>Mathematical Formulations :</strong></p><ul><li><strong><em>Chunk Formulation Condition :</em></strong></li></ul><p>We define a chunk as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPDVom99ZbMR8-ipek5_zA.jpeg" /></figure><p><strong>Implementation Strategy :</strong></p><pre>import nltk<br>from typing import List<br><br>def sentence_chunking(text:str, sentences_per_chunk: int=3) -&gt; List[str]:<br>    &quot;&quot;&quot;<br>    Splits the input text into chunks containing a fixed number of sentences<br><br>    Parameters:<br>    text (str): The input text to be chunked<br>    sentences_per_chunk (int): Number of sentences per chunk<br>                               Default is 3<br><br>    Returns:<br>    List[str]: A list of text chunks, each containing &#39;sentences_per_chunk&#39; sentences<br>    &quot;&quot;&quot;<br>    sentences = nltk.sent_tokenize(text)<br>    chunks = []<br>    <br>    for i in range(0, len(sentences), sentences_per_chunk):<br>        chunk = &quot; &quot;.join(sentences[i:i+sentences_per_chunk])<br>        chunks.append(chunk)<br>    <br>    return chunks</pre><p><strong>Advantages and Limitations :</strong></p><p><strong>Advantages</strong>: Semantic coherence, natural boundaries and fine-grained retrieval.</p><p><strong>Limitations</strong>: Variable chunk sizes, potential context fragmentation and computational overhead.</p><h4>3.2 Paragraph Based Chunking :</h4><p><strong>What is it ? :</strong></p><p>Paragraph based Chunking chunks documents based on paragraphs( not on any end of sentence or any token). It preserves topical coherence within larger units and group each paragraph until a token limit is reached.</p><p><strong>Useful when:</strong></p><ul><li>Text is naturally structured in paragraphs (e.g., articles, essays, blogs)</li><li>You want to preserve <strong>semantic units</strong> larger than sentences which are possible through paragraphs.</li><li>Chunks should maintain topic continuity (usually paragraphs represent single subtopics)</li></ul><p><strong>Mathematical Formulation :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*1WPn0y7tc7OU5MJM8k-G9g.jpeg" /></figure><p><strong>Implementation Strategy :</strong></p><pre>import nltk <br>from typing import List<br><br>def paragraph_chunking(text, max_paragraph_length=1000):<br>    &quot;&quot;&quot;<br>    Splits the input text into chunks based on paragraph breaks, with optional <br>    secondary chunking for long paragraphs.<br><br>    Parameters:<br>    text (str): The input text to be chunked.<br>    max_paragraph_length (int): Maximum character length allowed for a paragraph chunk. <br>                                 Longer paragraphs are further split using sentence-level chunking.<br><br>    Returns:<br>    List[str]: A list of text chunks where each chunk is either a paragraph or a sub-paragraph <br>               (if the original paragraph exceeds the specified length).<br>    &quot;&quot;&quot;<br>    paragraphs = text.split(&#39;\n\n&#39;)<br>    chunks = []<br>    for para in paragraphs:<br>        if len(para) &lt;= max_paragraph_length:<br>            chunks.append(para.strip())<br>        else:<br>            # Apply secondary chunking (e.g., sentence-based)<br>            sub_chunks = sentence_chunking(para)<br>            chunks.extend(sub_chunks)<br>    return [chunk for chunk in chunks if chunk]</pre><p><strong>Advantages and Limitations :</strong></p><p>Advantages :</p><ul><li>Simple and intuitive to implement</li><li>Maintain natural and semantic boundaries.</li><li>Works well with structured documents with no sentence breakage.</li></ul><p>Limitations :</p><ul><li>Very long paragraphs may exceed model max token limits.</li><li>Not efficient for tasks needing fixed input length.</li></ul><h3>3.3 Page Based Chunking :</h3><h4>What is it ?</h4><p>It is a document processing technique which splits the texts in to chunks where each chunk corresponds a single page. The process involves identifying page breaks within the document (page no. or section breaks) and creating a new chunk at each break.</p><p><strong>Useful when :</strong></p><ul><li>Processing a book or report where each page corresponds to a distinct context.</li><li>It is also useful when we want to index and document each page on its own.</li></ul><p><strong>Mathematical Formulation :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*x5TZo-UCvzxDegYsRZB5-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*Jt1GQTEls9GtoFMBfEKL-Q.png" /></figure><h4>Implementation Strategy :</h4><pre>def page_chunking(pdf_document):<br>    &quot;&quot;&quot;<br>    Splits a PDF document into chunks, where each chunk represents the text content of a single page.<br><br>    Parameters:<br>        pdf_document (object): A PDF document object (e.g., from PyMuPDF, pdfplumber, or similar library)<br>                               that provides a `.pages` attribute, where each page has an `extract_text()` method.<br><br>    Returns:<br>        list[dict]: A list of dictionaries, each containing:<br>            - &#39;content&#39; (str): Extracted text from the page.<br>            - &#39;page_number&#39; (int): The page number (1-based index).<br>            - &#39;metadata&#39; (dict): Metadata for the page, extracted via `extract_page_metadata(page)`.<br><br>    Notes:<br>        - Skips pages that have no text or contain only whitespace.<br>        - Requires `extract_page_metadata(page)` to be defined externally.<br>    &quot;&quot;&quot;<br>    chunks = []<br>    for page_num, page in enumerate(pdf_document.pages):<br>        text = page.extract_text()<br>        if text.strip():<br>            chunks.append({<br>                &#39;content&#39;: text,<br>                &#39;page_number&#39;: page_num + 1,<br>                &#39;metadata&#39;: extract_page_metadata(page)<br>            })<br>    return chunks</pre><h4><strong>Advantages and Limitations :</strong></h4><p><strong>Advantages :</strong></p><ul><li>Ensures that each chunk is self-contained according to the size of the content or page.</li><li>Relatively very easy to implement, especially if you have structured documents.</li><li>Minimise risk of unrelated content coming in to the same chunk</li></ul><p><strong>Disadvantages :</strong></p><ul><li>Chunks may be shortened if the page content is relatively small or contains only whitespaces.</li><li>This strategy does not deliver optimal results if contexts of the same information is spanned across multiple documents</li></ul><h3>3.4. Fixed Sized Chunking</h3><h4>What is it ?</h4><p>Fixed Size Chunking is another very easy to implement chunking strategy. The process involves creating uniformly sized segments based on character counts, token counts or maybe other measurable quantities which are pre-defined.</p><p><strong>Useful When :</strong></p><ul><li>There is a memory constrained system and including randomness in chunking to an extent is not possible.</li><li>When task involves batch processing making up for uniform processing times.</li></ul><p>Mathematical Implementation :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*GdW3ptdHNoEiQElW8Pxasg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*2BTKS3W5MbmLCy6TLaqv4A.png" /></figure><h4>Implementation Strategy :</h4><pre>def fixed_size_chunking(text, chunk_size=1000, overlap=200):<br>    &quot;&quot;&quot;<br>    Splits the input text into fixed-size overlapping chunks.<br><br>    Parameters:<br>    ----------<br>    text : str<br>        The input text to be divided into chunks.<br>    chunk_size : int, optional (default=1000)<br>        The maximum length of each chunk.<br>    overlap : int, optional (default=200)<br>        The number of overlapping characters between consecutive chunks.<br><br>    Returns:<br>    -------<br>    List[str]<br>        A list of text chunks, each of up to `chunk_size` characters, with `overlap` characters <br>        overlapping between adjacent chunks.<br><br>    Example:<br>    -------<br>    &gt;&gt;&gt; fixed_size_chunking(&quot;abcdefghijklmnopqrstuvwxyz&quot;, chunk_size=10, overlap=2)<br>    [&#39;abcdefghij&#39;, &#39;ijklmnopqr&#39;, &#39;qrstuvwxyz&#39;]<br>    &quot;&quot;&quot;<br>    chunks = []<br>    start = 0<br>    while start &lt; len(text):<br>        end = min(start + chunk_size, len(text))<br>        chunk = text[start:end]<br>        chunks.append(chunk)<br>        start += chunk_size - overlap<br>    return chunks</pre><h4>Advantages and Limitations :</h4><p><strong>Advantages :</strong></p><ul><li>This chunking strategy is very easy to implement. Also all chunks having same length make it relatively easier for batch processing in ML models.</li><li>It is relatively a faster process causing better option for parallel processing and also predictable memory allocation is possible.</li></ul><p><strong>Disadvantages :</strong></p><ul><li>Important context of a sentence may get lost due to predefined chunk splitting causing fall of the meaning — thus making it bad for sentences with meaningful structures.</li><li>If data does not divide evenly, may need to introduce padding which can add unnecessary noise to the data.</li></ul><h3>3.5. Sliding Window Chunking</h3><h4>What is it ?</h4><p>Sliding window chunking creates fix sized overlapping segments or windows. They move across the document with a predefined fixed stride which ensures context preservation across multiple documents.</p><p><strong>Useful When :</strong></p><ul><li>Maintenance of cross boundary relationships across multiple documents.</li><li>In time series analysis when we want to preserve the temporal continuity.</li></ul><p><strong>Mathematical Implementation :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vAiU-DAB4Hod9z3VWwzgvw.png" /></figure><p>Let:</p><ul><li>text = the input sequence (string or list of tokens)</li><li>chunk_size = size of each chunk</li><li>stride = number of tokens to move the window at each step.</li></ul><h4>Implementation Strategy :</h4><pre>def sliding_window_chunking(text, window_size=1000, stride=800):<br>    &quot;&quot;&quot;<br>    Splits the input text into overlapping chunks using a sliding window strategy.<br><br>    Parameters:<br>        text (str): The input text to be chunked.<br>        window_size (int): The size of each chunk (number of characters). Default is 1000.<br>        stride (int): The number of characters to move the window at each step. Default is 800.<br><br>    Returns:<br>        List[dict]: A list of dictionaries, each containing:<br>            - &#39;content&#39;: The chunked text.<br>            - &#39;start_pos&#39;: The starting character index of the chunk in the original text.<br>            - &#39;end_pos&#39;: The ending character index (exclusive) of the chunk in the original text.<br>    <br>    Example:<br>        &gt;&gt;&gt; sliding_window_chunking(&quot;abcdefghij&quot;, window_size=5, stride=3)<br>        [<br>            {&#39;content&#39;: &#39;abcde&#39;, &#39;start_pos&#39;: 0, &#39;end_pos&#39;: 5},<br>            {&#39;content&#39;: &#39;defgh&#39;, &#39;start_pos&#39;: 3, &#39;end_pos&#39;: 8},<br>            {&#39;content&#39;: &#39;ghij&#39;,  &#39;start_pos&#39;: 6, &#39;end_pos&#39;: 11}<br>        ]<br>    &quot;&quot;&quot;<br>    chunks = []<br>    for i in range(0, len(text) - window_size + 1, stride):<br>        chunk = text[i:i + window_size]<br>        chunks.append({<br>            &#39;content&#39;: chunk,<br>            &#39;start_pos&#39;: i,<br>            &#39;end_pos&#39;: i + window_size<br>        })<br>    return chunks</pre><p><strong>Advantages and Disadvantages :</strong></p><p><strong>Advantages :</strong></p><ul><li>Important information near the edge of a document does not get lost due to overlapping segments.</li><li>You can change window_size and stride to dynamically update the segment and optimise memory usage.</li><li>Used mostly in transformer-based models (GPT and BERT-based models) for QA and summarisation tasks.</li></ul><p><strong>Disadvantages :</strong></p><ul><li>Duplicate processing of some texts due to overlapping chunks may lead to inefficiencies.</li><li>More chunks can be equivalent to more memory thus can cause more training/inference time.</li></ul><h3>3.6. Structured Chunking :</h3><h4>What is it ?</h4><p>The next chunking strategy is the Structured Chunking which breaks documents into chunks based on meaning natural boundaries like :</p><ul><li>Paragraphs</li><li>Headings</li><li>Sections</li><li>Sentences</li></ul><p>Structured chunking respects semantics rather than individual character length.</p><p><strong>Useful When :</strong></p><ul><li>We want to leverage HTML function for Web Content Preprocessing</li><li>When we want to respect section hierarchies in technical documentation.</li></ul><p><strong>Mathematical Implementation :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caIKHmqGk9CndqqbBDFHCg.png" /></figure><p>Implementation Strategy :</p><pre>import re<br><br>def structured_chunking(text, delimiter=r&#39;\n\n&#39;, max_units_per_chunk=3):<br>    &quot;&quot;&quot;<br>    Splits input text into chunks based on structured boundaries like paragraphs or sentences.<br><br>    Parameters:<br>        text (str): The input text to be chunked.<br>        delimiter (str): Regex pattern to split the text (e.g., &#39;\n\n&#39; for paragraphs, &#39;\. &#39; for sentences).<br>        max_units_per_chunk (int): Number of units (e.g., paragraphs) to include per chunk.<br><br>    Returns:<br>        List[dict]: A list of dictionaries, each containing:<br>            - &#39;content&#39;: The chunked text.<br>            - &#39;start_unit&#39;: Index of the first unit in the chunk.<br>            - &#39;end_unit&#39;: Index of the last unit in the chunk (exclusive).<br>    <br>    Example:<br>        &gt;&gt;&gt; structured_chunking(&quot;Para1\n\nPara2\n\nPara3\n\nPara4&quot;, max_units_per_chunk=2)<br>        [<br>            {&#39;content&#39;: &#39;Para1\n\nPara2&#39;, &#39;start_unit&#39;: 0, &#39;end_unit&#39;: 2},<br>            {&#39;content&#39;: &#39;Para3\n\nPara4&#39;, &#39;start_unit&#39;: 2, &#39;end_unit&#39;: 4}<br>        ]<br>    &quot;&quot;&quot;<br>    units = re.split(delimiter, text)<br>    chunks = []<br>    for i in range(0, len(units), max_units_per_chunk):<br>        chunk_units = units[i:i + max_units_per_chunk]<br>        chunk = delimiter.join(chunk_units).strip()<br>        chunks.append({<br>            &#39;content&#39;: chunk,<br>            &#39;start_unit&#39;: i,<br>            &#39;end_unit&#39;: i + len(chunk_units)<br>        })<br>    return chunks</pre><p><strong>Advantages and Disadvantages :</strong></p><p><strong>Advantages</strong> :</p><ul><li>Chunks which gets created respects sentence/paragraph boundaries — leading to better contextual integrity.</li><li>No overlapping chunks thus less computation and efficient memory usage.</li><li>Easier to implement or visualise compared to fixed-size chunks.</li></ul><p><strong>Disadvantages</strong> :</p><ul><li>Chunk length can vary dramatically — which can cause an issue which training a Language model.</li><li>Sentence or paragraph boundaries can vary from different languages — which can cause the model to not be multilingual.</li></ul><h3>3.7. Keyword-Based Chunking :</h3><h4>What is it ?</h4><p>This is a rather interesting chunking strategy. It works something like it searches for specific keywords or phrases in the long documents. It breaks the documents in to smaller chunks based on those discrete topics.</p><p><strong>Useful When :</strong></p><ul><li>Relevant when we want to focus on Topic-Specific Retrieval</li><li>It serves compliance checking by focusing on regulatory targeted keywords.</li></ul><p><strong>Mathematical Implementation :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDXBb20d79CSaWvr6pdWVg.png" /></figure><pre>import re<br><br>def keyword_chunking(text, keywords, window_size=50):<br>    &quot;&quot;&quot;<br>    Splits text into chunks based on the presence of specified keywords, <br>    extracting a window of context around each keyword match.<br><br>    Parameters:<br>        text (str): The full input text.<br>        keywords (List[str]): List of keywords or phrases to search for.<br>        window_size (int): Number of characters to include before and after the keyword.<br><br>    Returns:<br>        List[dict]: A list of dictionaries, each containing:<br>            - &#39;keyword&#39;: The matched keyword.<br>            - &#39;content&#39;: The chunk of text surrounding the keyword.<br>            - &#39;start_pos&#39;: Start index of the chunk in the original text.<br>            - &#39;end_pos&#39;: End index (exclusive) of the chunk in the original text.<br>    <br>    Example:<br>        &gt;&gt;&gt; keyword_chunking(&quot;Python is great. Java is popular.&quot;, [&quot;Python&quot;, &quot;Java&quot;], 5)<br>        [<br>            {&#39;keyword&#39;: &#39;Python&#39;, &#39;content&#39;: &#39;Python is gr&#39;, &#39;start_pos&#39;: 0, &#39;end_pos&#39;: 12},<br>            {&#39;keyword&#39;: &#39;Java&#39;, &#39;content&#39;: &#39; is popular.&#39;, &#39;start_pos&#39;: 17, &#39;end_pos&#39;: 30}<br>        ]<br>    &quot;&quot;&quot;<br>    chunks = []<br>    for keyword in keywords:<br>        for match in re.finditer(re.escape(keyword), text, flags=re.IGNORECASE):<br>            start = max(match.start() - window_size, 0)<br>            end = min(match.end() + window_size, len(text))<br>            chunks.append({<br>                &#39;keyword&#39;: keyword,<br>                &#39;content&#39;: text[start:end].strip(),<br>                &#39;start_pos&#39;: start,<br>                &#39;end_pos&#39;: end<br>            })<br>    return chunks</pre><p><strong>Advantages and Disadvantages :</strong></p><p><strong>Advantages</strong> :</p><ul><li>It focuses only on relevant information — thus reliable and faster chunks.</li><li>One can adjust the window size dynamically after every use.</li><li>Great for search systems, information retrieval, or filtering large documents.</li></ul><p><strong>Disadvantages :</strong></p><ul><li>Important information not near by to a keyword may be lost.</li><li>It does not respect sentence/paragraph chunking if compound chunking is not done.</li><li>Multiple keyword cluttered together may overlap the chunks.</li></ul><h3>3.8. Recursive Chunking :</h3><h4>What is it ?</h4><p>Recursive chunking applies hierarchical segmentation, progressively subdividing chunks. It prioritizes breaking large documents at logical structural boundaries and recursively splitting further until a pre defined chunk size is met.</p><p><strong>Useful When :</strong></p><ul><li>We want the strategy to adapt to varying length of documents.</li><li>When there is hierarchical content meaning nested relationships can occur.</li><li>Commonly used in LangChain and other LLM pipelines to maintain system integrity.</li></ul><p><strong>Mathematical Implementation :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rRdsfmoBXRbjJ_yZWaqUw.png" /></figure><p><strong>Implementation Strategy :</strong></p><pre>def recursive_chunking(text, max_length=500, separators=None):<br>    &quot;&quot;&quot;<br>    Recursively splits text into chunks under a target size, <br>    using progressively smaller natural boundaries.<br><br>    Parameters:<br>        text (str): The input text to split.<br>        max_length (int): Maximum allowed length per chunk (characters or tokens).<br>        separators (List[str], optional): List of separators in decreasing granularity. <br>            Defaults to [&#39;\n\n&#39;, &#39;. &#39;, &#39; &#39;].<br><br>    Returns:<br>        List[str]: List of chunk strings, each within the max_length limit.<br><br>    Example:<br>        &gt;&gt;&gt; recursive_chunking(&quot;Paragraph one.\n\nParagraph two is long...&quot;, max_length=20)<br>        [&#39;Paragraph one.&#39;, &#39;Paragraph two is&#39;, &#39;long...&#39;]<br>    &quot;&quot;&quot;<br>    if separators is None:<br>        separators = [&#39;\n\n&#39;, &#39;. &#39;, &#39; &#39;]<br><br>    if len(text) &lt;= max_length:<br>        return [text.strip()]<br><br>    for sep in separators:<br>        if sep in text:<br>            parts = text.split(sep)<br>            chunks = []<br>            current_chunk = &quot;&quot;<br>            for part in parts:<br>                candidate = (current_chunk + sep + part).strip() if current_chunk else part.strip()<br>                if len(candidate) &lt;= max_length:<br>                    current_chunk = candidate<br>                else:<br>                    if current_chunk:<br>                        chunks.extend(recursive_chunking(current_chunk, max_length, separators[1:]))<br>                    current_chunk = part.strip()<br>            if current_chunk:<br>                chunks.extend(recursive_chunking(current_chunk, max_length, separators[1:]))<br>            return chunks<br><br>    # Fallback: force split if no separator found<br>    return [text[i:i+max_length] for i in range(0, len(text), max_length)]</pre><p><strong>Advantages and Disadvantages :</strong></p><p><strong>Advantages</strong> :</p><ul><li>It tries to split along meaningful boundaries at first. (first paragraph, then punctuations and then words).</li><li>It guarantees the chunks will never exceed your max model token size.</li><li>It avoids cutting in the middle of sentences unless absolutely necessary.</li></ul><p><strong>Disadvantages :</strong></p><ul><li>Some chunks can turn out much smaller than the pre defined chunk size.</li><li>Context overlapping is not possible unless explicitely done so.</li><li>If texts lag separators, it will just hard-split.</li></ul><h3>3.9. Token Based Chunking :</h3><h4><strong>What is it ?</strong></h4><p><strong>Recursive Chunking</strong> is a text-splitting strategy that tries to keep chunks <strong>under a target size</strong> by recursively splitting text along <strong>natural boundaries</strong> (paragraphs → sentences → words).<br> If the chunk is still too big, it splits again until it fits the size limit.</p><p>This is commonly used in <strong>LangChain</strong> and other LLM pipelines to maintain semantic integrity while respecting token/character limits.</p><p><strong>Useful when :</strong></p><p>1. You Have a Token Limit to Respect. LLMs like GPT-4 or Claude have a <strong>maximum context length</strong> (e.g., 8k, 32k tokens). Recursive chunking ensures <strong>no chunk exceeds this limit</strong>, so your prompt never gets rejected.</p><p>2. You Want to Preserve Semantic Meaning. Useful for <strong>RAG pipelines</strong>, <strong>Q&amp;A systems</strong>, or <strong>summarisation</strong> where breaking mid-sentence can hurt performance. Keeps text as <strong>intact as possible</strong> by splitting at larger boundaries first.</p><p>3. You’re Working With Mixed-Length Documents.</p><p><strong>Mathematical Implementation :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkhQFYjjXBgqMo07c0qLWQ.png" /></figure><p><strong>Implementation strategy :</strong></p><pre>def recursive_chunking(text, max_length=500, separators=None):<br>    &quot;&quot;&quot;<br>    Recursively splits text into chunks under a target size, <br>    using progressively smaller natural boundaries.<br><br>    Parameters:<br>        text (str): The input text to split.<br>        max_length (int): Maximum allowed length per chunk (characters or tokens).<br>        separators (List[str], optional): List of separators in decreasing granularity. <br>            Defaults to [&#39;\n\n&#39;, &#39;. &#39;, &#39; &#39;].<br><br>    Returns:<br>        List[str]: List of chunk strings, each within the max_length limit.<br><br>    Example:<br>        &gt;&gt;&gt; recursive_chunking(&quot;Paragraph one.\n\nParagraph two is long...&quot;, max_length=20)<br>        [&#39;Paragraph one.&#39;, &#39;Paragraph two is&#39;, &#39;long...&#39;]<br>    &quot;&quot;&quot;<br>    if separators is None:<br>        separators = [&#39;\n\n&#39;, &#39;. &#39;, &#39; &#39;]<br><br>    if len(text) &lt;= max_length:<br>        return [text.strip()]<br><br>    for sep in separators:<br>        if sep in text:<br>            parts = text.split(sep)<br>            chunks = []<br>            current_chunk = &quot;&quot;<br>            for part in parts:<br>                candidate = (current_chunk + sep + part).strip() if current_chunk else part.strip()<br>                if len(candidate) &lt;= max_length:<br>                    current_chunk = candidate<br>                else:<br>                    if current_chunk:<br>                        chunks.extend(recursive_chunking(current_chunk, max_length, separators[1:]))<br>                    current_chunk = part.strip()<br>            if current_chunk:<br>                chunks.extend(recursive_chunking(current_chunk, max_length, separators[1:]))<br>            return chunks<br><br>    # Fallback: force split if no separator found<br>    return [text[i:i+max_length] for i in range(0, len(text), max_length)]</pre><p><strong>Advantages and Disadvantages :</strong></p><p><strong>Advantages</strong> :</p><p><strong>Token Limit Safety</strong></p><ul><li>Perfect for LLMs — ensures no chunk exceeds context size.</li></ul><p><strong>Exact Size Control</strong></p><ul><li>More precise than character-based chunking (since 1 char ≠ 1 token).</li></ul><p><strong>Model-Compatible</strong></p><ul><li>Works directly with tokenizers used by GPT, Claude, LLaMA, etc.</li></ul><p><strong>Useful for Cost Control</strong></p><ul><li>Prevents sending unnecessary tokens to the model, lowering API costs.</li></ul><p><strong>Disadvantages :</strong></p><p><strong>Tokenizer Dependency</strong></p><ul><li>Must use the <strong>exact tokenizer</strong> of the target model for accuracy.</li></ul><p><strong>Semantic Cuts Possible</strong></p><ul><li>May split mid-sentence or mid-paragraph if you don’t add overlap.</li></ul><h3>Final Conclusion and My Thoughts :</h3><p>After exploring these different chunking strategies — sliding window, structured, keyword-based, recursive, token-based, and even sentence-based approaches — one thing became clear: <strong>there is no one-size-fits-all method</strong>. The “best” strategy depends on your <strong>document type</strong>, <strong>retrieval goals</strong>, and the <strong>LLM’s constraints</strong>.</p><p>In my legal document search engine case, the shift from arbitrary token splits to <strong>sentence-based chunking</strong> completely changed the game. Not only did it <strong>preserve semantic meaning</strong>, but it also drastically reduced hallucinations and improved the precision of the retrieved answers.</p><p>The biggest takeaway? <strong>Chunking is not just preprocessing — it’s part of the intelligence layer in RAG</strong>. A well-thought-out chunking strategy can make the difference between a confused, rambling model and a focused, accurate one.</p><p>So, next time you’re building a RAG pipeline, don’t just think about embeddings and vector databases. Think about <strong>how you’re feeding the model its food</strong>.<br> Because if the chunks are messy, the answers will be messy too.</p><p>For me, chunking went from being a “minor technical detail” to a <strong>core design decision</strong> that I now spend as much time fine-tuning as the model itself. And trust me when i say this — that mindset shift alone has saved me countless hours of debugging and frustration.</p><blockquote><strong><em>Meet you in my next blog — until then, keep your chunks clean and your context sharper than a judge’s gavel.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54508fa87d3f" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/varieties-of-rag-chunking-techniques-a-comprehensive-analysis-of-strategies-for-downstream-task-54508fa87d3f">Varieties of RAG Chunking Techniques: A Comprehensive Analysis of Strategies for Downstream Task…</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Language Barriers: The Frontier of Multilingual LLMs and Cross-Lingual Mastery]]></title>
            <link>https://aws.plainenglish.io/breaking-language-barriers-the-frontier-of-multilingual-llms-and-cross-lingual-mastery-3dfa172c8628?source=rss-34a20cdf5e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dfa172c8628</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Subhasmukherjee]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 04:49:18 GMT</pubDate>
            <atom:updated>2025-08-20T00:49:58.334Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction :</strong></h3><p>In Tokyo, Aiko, a young entrepreneur named Asahi Haruto was facing issues expanding his business globally. What was the biggest hurdle ? Language.<strong> </strong>With users ranging from the vibrant markets of Marrakech to the tech hubs of San Francisco, Aiko’s app was in need to communicate seamlessly across various languages, each with its own grammar and cultural contexts.</p><p>Meanwhile, in a small café in Paris, a bookshop owner was facing a very niche problem. His works spans to various languages and centuries and was nothing short of a marvellous treasure for human history. Nonetheless sharing this knowledge was problematic due to nuanced language barriers. He dreamt of a tool which will not only be able to translate languages but will identify the underlying context before translating it.</p><p>Here, let me introduce you to Multilingual Large Language Models (LLMs), a groundbreaking discovery in. the field of AI. Unlike previous models, these models understand, generate, and contextualise language in a remarkably human-like way. These models are trained on very diverse datasets with numerous languages which helps the models to not only generate but also generalize content with proper understanding of the context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*oeZon44I7ATW8U57.png" /></figure><h3><strong>Architectural Innovation :</strong></h3><p><strong>The advancement in Multi Lingual Language Models is a result of numerous architecture innovations. </strong>These advancements have not only helped LLMs to work better but also helped them to generalise well on diverse languages. Let us go through a few of those innovations which helped multilingual LLMs success to this extent :</p><ol><li><strong>Shared Multilingual Vocabulary : </strong>Probably the most convenient innovation when comparing with monolingual peers. The main advantage being able to translate multiple languages with an unified vocabulary. This approach helps the model to translate various languages in a single framework.</li><li><strong>Language Agnostic Representations : </strong>Language Agnostic Representation is another critical innovation in the same field. It transcends in understanding the essence of the language — by focusing not only on the translation but also on universal features of languages like syntax, semantic knowledge and context understanding.</li><li><strong>Cross-Lingual Embeddings</strong> : Cross-Lingual Embeddings are the embeddings which puts texts despite of its language in to a shared vector space. One of the features of Language Models is Next Sentence Prediction(NSP). This shared vector space does helps these models leverage similarities between various languages.</li><li><strong>Transformer Architecture :</strong> The adoption and adaptation of the transformer architecture have been significant in the development of multilingual language models. Transformers with its most important feature being self-attention helps model to understand its relationship with different tokens in long and short sequences. This capability is crucial for handling the complexities and nuances of multiple languages, as it enables the model to capture long-range dependencies and contextual information across languages.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*EGTrt--_zmLVr0G9g-iwlQ.png" /></figure><h3>Cross-Lingual Transfer Learning: Mechanisms and Techniques</h3><p>Cross-Lingual Transfer learning is a way of leveraging knowledge in one language to improve the performance of models in other languages. Now, lets talk about a few cross lingual mechanisms below :</p><ol><li><strong>Zero Shot Cross Lingual Transfer learning :</strong> One of the most basic techniques is the Zero shot learning. The mechanism works like the model is trained on one language and is applied on another language without any additional training in the targeted language. This technique relies on the underlying similarities between languages, such as shared linguistic structures or common semantic meanings. Thus, languages which differ too much in syntax and semantics are not handled properly.</li><li><strong>Few-Shot Cross Lingual Transfer Learning :</strong> The next technique I would like to talk about is Few-Shot Cross Lingual Transfer Learning. This technique is different in a way that it is trained on a small dataset before translating on the target language. This helps the model adapt to nuances and work much better when comparable to zero shot learning.</li><li><strong>Multi-lingual Pre training </strong>: Multilingual pre-training involves training a language model on a large corpus of text data from multiple languages simultaneously. This technique helps the model learn shared representations and patterns across languages, helping in better transfer learning capabilities. Models like mBERT (Multilingual BERT) and <strong>XLM-RoBERTa </strong>(Cross-lingual Language Model — RoBERTa) are examples of multilingual pre-trained models.</li><li><strong>Cross-Lingual Knowledge Distillation </strong>: Knowledge Distillation is a process through which a smaller and efficient model(generally a student model) is trained to replicate the behaviour of a relatively larger model. In a cross-lingual context, knowledge distillation can be used to transfer knowledge from a high-resource language model to a low-resource language model which significantly reduces both computational time and save space. This approach helps in creating efficient and effective models for languages with limited data.</li></ol><p>These mechanisms and many other techniques are paving the way for more inclusive and effective language models.</p><h3>Challenges in Multilingual Model Training</h3><p>Training Multilingual Large Language Models (LLMs) can be quite challenging when dealing with multiple languages in a single framework. Here are some key drawbacks associated with training such models :</p><ol><li><strong>Data Imbalance across Languages </strong>: High-resource languages such as <strong>English, Spanish</strong> and <strong>Chinese</strong> has huge amount of texts ready and available to be trained on the data. On the other hand low-resource languages lack in providing training data. This makes the model biased towards the high-resource language. Further, to mitigate this problem weights are to be initialised on the minor class so the model gives equal importance to both of them.</li><li><strong>Handling Diverse Scripts and Language Structures </strong>: Not only language syntax and semantic nuances there is vast diversity in how each language is written. Some languages are written from right to left while other languages <strong>(Sumerian, Ancient Egypt Hieroglyphs)</strong>follow logographic approach. Some languages <strong>(Thai and Lao Scripts)</strong> do not even have a specific boundary or word spacing in between. Handling such diversity in structure could be a hassle for models.</li><li><strong>Computational Resources Requirements </strong>: Training Large Language Models is not only time-consuming but require a huge amount of computational resources. This happens mainly because of the vast amount of parameters ranging from a few millions to almost <strong>1.8 trillion</strong> <strong>parameters</strong> in <strong>GPT‑4o (OpenAI) (The Largest LLM recorded till date.) <br></strong>Loading and fine-tuning on such huge diversified language data can be very challenging and require very high end devices to work properly.</li></ol><p>4. <strong>Ethical and Cultural Considerations : </strong>Finally, training multilingual models involves finding ethical and cultural considerations. Models must be designed and trained to respect cultural sensitivities, avoid perpetuating stereotypes, and ensure fair representation across languages and dialects. This requires diverse and inclusive training data, as well as careful consideration by proper handling of sensitive and racist content either by filtering through a <strong>SLM</strong> or the rather more time-consuming but more accurate human intervention to ensure no bias of model’s output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*OXpp86gBM6lc7Fgj0v94_w.png" /></figure><h3>Case Studies of Successful Multilingual Models</h3><p>The development of multilingual language models has major advancements, with many models being able to understand and generate content across multiple languages. Here, some models are to be looked upon through their training methods, evaluating their metrices and discussing real-world applications.</p><h4><a href="https://github.com/google-research/bert/blob/master/multilingual.md">mBERT (Multilingual BERT)</a></h4><p><strong>Training Methodology:</strong></p><ul><li>mBERT, or Multilingual BERT, is an extension of the original BERT (Bidirectional Encoder Representations from Transformers) model. It is trained on a vast dataset containing over 100 languages, using the same architecture and training as done in BERT which is masked language modelling and next sentence prediction.</li><li>The model leverages a shared WordPiece vocabulary that includes subword units from all languages, enabling it to handle a wide range of linguistic variations.</li></ul><p><strong>Performance Benchmarks:</strong></p><ul><li>mBERT has shown impressive performance on various cross-lingual tasks, including natural language inference, question answering, and named entity recognition. It has set benchmarks for zero-shot cross-lingual transfer, where the model is evaluated on languages not included in the fine-tuning process.</li><li>While mBERT performs well on many tasks, its performance can vary significantly across languages, often favoring languages with more representation in the training data.</li></ul><p><strong>Real-World Applications:</strong></p><ul><li>mBERT has been applied in various cross-lingual applications, such as sentiment analysis, document classification, and information retrieval, where understanding text in multiple languages is crucial.</li><li>Its ability to perform zero-shot cross-lingual tasks makes it valuable for deploying NLP applications in low-resource languages where labeled data is scarce.</li></ul><h4>XLM-RoBERTa (Cross-lingual Language Model — RoBERTa)</h4><p><strong>Training Methodology:</strong></p><ul><li>XLM-RoBERTa builds on the RoBERTa model, which is an optimized version of BERT. It is trained on a significantly larger and more diverse dataset, encompassing over 100 languages and 2.5 TB of filtered CommonCrawl data.</li><li>The model uses a modified training objective that focuses on masked language modeling, similar to BERT, but with larger batch sizes and longer training times to improve performance.</li></ul><p><strong>Performance Benchmarks:</strong></p><ul><li><a href="https://huggingface.co/docs/transformers/en/model_doc/xlm-roberta">XLM-RoBERTa</a> has achieved state-of-the-art results on various cross-lingual benchmarks, including XNLI (Cross-lingual Natural Language Inference) and MLQA (Multilingual Question Answering).</li><li>It has demonstrated strong performance across a wide range of languages, including low-resource ones, making it one of the most robust multilingual models available.</li></ul><p><strong>Real-World Applications:</strong></p><ul><li>XLM-RoBERTa has been used in applications requiring multilingual understanding, such as cross-lingual document retrieval, multilingual sentiment analysis, and global content moderation.</li><li>Its robustness and versatility make it suitable for deploying NLP solutions in multinational corporations, social media platforms, and customer support systems.</li></ul><h4><a href="https://huggingface.co/docs/transformers/en/model_doc/t5">T5 (Text-to-Text Transfer Transformer)</a></h4><p><strong>Training Methodology:</strong></p><ul><li>T5 reframes all NLP tasks into a unified text-to-text format, where the input and output are always text strings. This approach allows for a consistent training objective across diverse tasks and languages.</li><li>The model is trained on a multilingual corpus, using a combination of supervised and unsupervised learning objectives to handle various tasks, including translation, summarization, and question answering.</li></ul><p><strong>Performance Benchmarks:</strong></p><ul><li>T5 has shown strong performance on a wide range of NLP tasks, including multilingual ones. Its text-to-text framework allows for easy adaptation to new tasks and languages, making it highly versatile.</li><li>The model’s performance is particularly notable in tasks requiring text generation, where it can leverage its understanding of multiple languages to produce coherent and contextually appropriate outputs.</li></ul><p><strong>Real-World Applications:</strong></p><ul><li>T5 has been applied in multilingual content generation, automated translation services, and cross-lingual information synthesis, where generating text in multiple languages is essential.</li><li>Its flexibility and adaptability make it valuable for applications in dynamic and multilingual environments, such as global news aggregation and multilingual chatbots.</li></ul><h3>Ethical Considerations and Bias :</h3><p>When discussing about Ethical Considerations and Bias it’s important to delve into the complexities that arise while deploying such multi lingual models.</p><p><strong>Ethical Concerns :</strong></p><ol><li>Ensure that the model is properly trained on highly diversified languages ranging not only on widely spoken languages but also on minority and endangered languages.</li><li>Must be transparent about the sources from where the data is been collected, stored and trained with. One must align their work according to the<strong> General Data Protection Regulation (GDPR) </strong>which focus on data privacy and security.</li><li>Make efforts to understand the decision making process is explainable and does not hallucinate. The users should have a general sense about why the LLM is thinking and giving that particular answer.</li></ol><p><strong>Addressing Bias :</strong></p><ol><li>Regular audit should be done on the training to ensure no unnecessary bias towards <strong>gender, economy, race</strong> and other demographic factors.</li><li>Use a variety of training data to ensure proper compliance covering a huge range of culture and their corresponding language dialects. <br>One can use <strong>adversarial - debiasing</strong> ,<strong> re-weighting training data</strong> and <strong>fairness aware training data</strong>.</li><li>Different evaluation metrics could be introduced to maintain proper fairness across different languages and <strong>demographic groups</strong>. Make sure the model gives equitable performance meaning it gives equal importance to every group with no favour towards one particular group.</li></ol><h3>Evaluation Metrics and Benchmarks :</h3><ol><li><strong>Perplexity</strong> : The Perplexity is a common metric that is used to measure how well a probability distribution predicts a sample. <br><em>Formula :</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*qHi8QFjE30s76KA6jsoRWw.png" /></figure><ul><li><em>Explanation</em><strong>:</strong> W is the test set, N is the total number of words, and p(wi∣w1,…,wi−1) is the conditional probability of the word wi.</li></ul><p>2. <strong>BLEU Score : </strong>The BLEU Score <strong>(Bilingual Evaluation Understudy)</strong> is an evaluation metric that<strong> </strong>is<strong> </strong>used to evaluate the similarity between the machine translated text and a high quality reference text. The BLEU Score ranges from 0 to 1 where ‘1’ indicates a perfect match and ‘0’ indicats no overlap. <br><em>Formula :</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*dbA7S9FtqDfaRgFMtjIJqA.png" /></figure><ul><li><em>Explanation:</em> precision is the precision for n-grams, and N is the maximum n-gram order.</li></ul><p>3<strong>. ROUGE Score : </strong>This set of metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation. ROUGE metrics range between 0 and 1, with higher scores indicating higher similarity between the automatically produced summary and the reference.<br><em>Formula :</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*2V25APSV99z88aIViJVGzg.png" /></figure><ul><li><strong>Explanation:</strong> gram is an n-gram, and Count<em>match</em>​(gram<em>n</em>​) is the number of times an n-gram co-occurs in the candidate and reference summaries.</li></ul><h3>The Future of Multilingual LLMs :</h3><ol><li><strong>Improved Language Coverage:</strong></li></ol><ul><li><strong>Expansion to Low-Resource Languages:</strong> Future LLMs are expected to cover a broader range of languages, including low-resource and endangered languages. This expansion will help preserve linguistic diversity and provide technology access to a more significant portion of the global population.</li><li><strong>Dialects and Variants:</strong> Enhanced models will better understand and generate various dialects and language variants, improving communication within linguistically diverse communities.</li></ul><p><strong>2. Enhanced Cross-Lingual Understanding:</strong></p><ul><li><strong>Zero-Shot and Few-Shot Learning:</strong> Advances in zero-shot and few-shot learning will enable models to perform tasks in languages they were not explicitly trained on, leveraging knowledge from high-resource languages.</li><li><strong>Contextual and Cultural Understanding:</strong> Future models will have a deeper understanding of cultural contexts, idioms, and nuances, leading to more accurate and culturally sensitive translations and interactions.</li></ul><p><strong>3. Multimodal Capabilities:</strong></p><ul><li><strong>Integration with Other Modalities:</strong> Multilingual LLMs will increasingly integrate with other modalities such as vision, speech, and gesture, enabling more comprehensive and context-aware applications.</li><li><strong>Multimodal Translation:</strong> Models will be capable of translating not just text but also images, videos, and other forms of media, providing a richer and more immersive cross-lingual experience.</li></ul><p><strong>4. Real-Time Translation and Communication:</strong></p><ul><li><strong>Instantaneous Translation:</strong> Future LLMs will provide real-time translation with minimal latency, facilitating seamless communication in international meetings, travel, and customer support.</li><li><strong>Simultaneous Interpretation:</strong> Advances in simultaneous interpretation will enable real-time translation of spoken language, making multilingual conferences and events more accessible.</li></ul><p><strong>5. Personalisation and Adaptation:</strong></p><ul><li><strong>User-Specific Models:</strong> LLMs will adapt to individual users’ language preferences, styles, and needs, providing personalized language assistance and learning experiences.</li><li><strong>Continuous Learning:</strong> Models will continuously learn and adapt from user interactions, improving their performance and accuracy over time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*thPvKTg9M7k39cmYasDZ4g.png" /></figure><h3>User Experiences</h3><p>Understanding how users are experiencing Multilingual LLMs, their explainability and their drawbacks will only help in further improvement of future models. Here are some aspects of user experiences with multilingual LLMs:</p><ol><li><strong>Accessibility and Usability:</strong></li></ol><ul><li><strong>Ease of Use:</strong> Users most of the time appreciate LLMs which are easy to integrate through IDEs in their current working enviorment and projects. Thus, LLMs with easy user interface and clean handling is much more user friendly.</li><li><strong>Language Support:</strong> Users from diverse linguistic backgrounds value the ability to interact with technology in their native language. Support for multiple languages and dialects can significantly enhance accessibility.</li></ul><p><strong>2. Performance and Accuracy:</strong></p><ul><li><strong>Translation Quality:</strong> Users often prefer not linear translations, rather context and syntax aware proper translations. Such accurate translations is much appreciated by users.</li><li><strong>Response Time:</strong> Immediate responses are much more acknowledged by users especially in fields where users need fast interactions which could be a customer support system.</li></ul><p><strong>3. Cultural Sensitivity:</strong></p><ul><li><strong>Cultural Nuances:</strong> Users appreciate models that understand and respect cultural nuances, idioms, and context-specific expressions. Culturally sensitive models foster better communication and avoid misunderstandings.</li><li><strong>Bias and Fairness:</strong> Users are relatively aware of cultural biases and sensitive content and admires if those topics are handled correctly. Fair representation and inclusivity across languages and cultures are essential for positive user experiences.</li></ul><p><strong>4. Personalisation:</strong></p><ul><li><strong>Customisation:</strong> Proper customisation according to the users needs mainly through domain-specific topics ease in their work flow overall generating a pragmatic view of the user towards the model.</li><li><strong>Adaptive Learning:</strong> Models that adapt and improve based on user interactions provide a more personalised and effective experience.</li></ul><h3>Conclusion</h3><p>Multilingual Language Models (LLMs) represent a significant advancement in the field of natural language processing, which holds the potential to break down language barriers and help share and receive informations in a more convinient way. As these models continue to evolve, several key areas will shape their development and impact:</p><p><strong>Technological Advancements:</strong> Future advancements in model architectures, training methods, and multimodal capabilities will surely increase the performance and versatility of multilingual llms.</p><p><strong>Ethical Considerations:</strong> Addressing biases, ensuring inclusivity, and promoting fairness will be crucial for developing ethical and responsible language models.</p><p><strong>User-Centric Design:</strong> Focusing on user experiences, accessibility, and personalisation will ensure that multilingual LLMs meet the diverse needs of global users.</p><p><strong>Collaborative Efforts:</strong> Open-source initiatives, community engagement, and interdisciplinary collaborations will drive innovation and ensure that multilingual LLMs are developed in a transparent and inclusive manner.</p><p><strong>Real-World Impact:</strong> The use of multilingual LLMs in different domains like healthcare, business and sales will change how we communicate and share information among languages.</p><blockquote>As we look to the future, the continued development and responsible deployment of multilingual LLMs hold immense promise for creating a more connected and inclusive world. By addressing the challenges and leveraging the opportunities, we can harness the full potential of these powerful tools to bridge linguistic divides and promote cross-cultural understanding.</blockquote><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dfa172c8628" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/breaking-language-barriers-the-frontier-of-multilingual-llms-and-cross-lingual-mastery-3dfa172c8628">Breaking Language Barriers: The Frontier of Multilingual LLMs and Cross-Lingual Mastery</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Map-Based Learning with SOMs for Real-Time Anomaly Detection in Finance]]></title>
            <link>https://ai.plainenglish.io/dynamic-map-based-learning-with-soms-for-real-time-anomaly-detection-in-finance-35ebcd1ca23b?source=rss-34a20cdf5e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/35ebcd1ca23b</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Subhasmukherjee]]></dc:creator>
            <pubDate>Sun, 18 May 2025 16:25:12 GMT</pubDate>
            <atom:updated>2025-08-20T08:00:51.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*WZ1mDvylku6g7n4FNhm18Q.png" /></figure><blockquote><strong>A Real Financial Anomaly Scenario </strong><br>In March 2023, Silicon Valley Bank (SVB) collapsed in what became the second largest bank failure in US history. The implosion was driven by a rapid liquidity crunch, poor interest rate risk management, and a modern-day bank run. While the event unfolded abruptly, early indicators such as deteriorating liquidity ratios, rising deposit outflows, market sentiment shifts, and unrealized losses on long-term bond holdings were already present — making it an ideal case for anomaly detection using Self-Organizing Maps (SOMs).</blockquote><h4><strong>Problem Statement<br></strong>Financial data often deal with real time, high-frequency and unstructured data. Anomaly detection with SOMs pose a few notable shortcomings —</h4><p><strong>Concept Drift</strong>: When the data distribution changes due to macroeconomic shifts, model predictions become obsolete.</p><p><strong>Lack of Interpretability</strong>: Black-box models make it hard for risk analysts and compliance officers to understand <strong>why</strong> an anomaly was flagged.</p><p>For example, an autoencoder might flag a sharp rise in credit risk scores but won’t explain which features changed — or how severely.</p><p><strong>Thesis</strong><br><strong>Self-Organizing Maps (SOMs)</strong> — especially when implemented with <strong>dynamic, online learning mechanisms</strong> — offer :</p><ul><li>Continuous learning capabilities (ideal for real-time updates)</li><li>Visual interpretability (U-Matrix and component planes)</li><li>Intuitive outlier detection (via distance metrics)</li></ul><p>This makes them a perfect fit for real-time financial anomaly detection and decision support.</p><h3><strong>Why Financial Anomaly Detection is considered complex ?</strong></h3><p>Imagine detecting fraud in a bank:</p><ul><li>One transaction may appear normal at first.</li><li>But when viewed in context — like time of day, location, typical transaction history, and velocity — it might be highly unusual.</li></ul><p>Financial anomaly detection involves:</p><ul><li><strong>Multivariate data</strong>: Liquidity, deposits, bond exposure, customer transactions</li><li><strong>Dynamic environments</strong>: Policy rate changes, market volatility</li><li><strong>Real-time response</strong>: Delayed detection could lead to billion-dollar losses</li></ul><h3><strong>What exactly are Self-Organizing Maps ?</strong></h3><p>A Self-organizing map also known as <strong>Kohonen Maps </strong>is a type of unsupervised neural network introduced by <strong>Teuvo Kohonen</strong> in 1980s. They are used primarily to project high-dimensional data in to low dimensional 2d grid. Unlike typical neural networks which are trained with labelled data, SOMs learn the intrinsic patterns within the data without needing any predefined labelled data at all.</p><p><strong>Analogy</strong> — Think of projecting our round globe in to a flat map(Not a flat earth believer ). What happens is that you loose the dimensions but become able to store the neighborhood structural relationships.</p><p>A SOM consists of neurons arranged in a grid and each neuron has the same weight vector as that of the input data. The grid of “maps” organize itself based on the input data patterns, hence the name <strong>Self-Organizing Maps.</strong></p><p><strong><em>Python Example :</em></strong></p><pre><br>       import numpy as np<br><br>class DynamicSOM:<br>    def __init__(self, x, y, input_len, learning_rate=0.5, sigma=None):<br>        &quot;&quot;&quot;<br>        Initialize the Self-Organizing Map (SOM).<br><br>        Parameters:<br>        - x, y (int): Dimensions of the SOM grid<br>        - input_len (int): Dimensionality of the input data<br>        - learning_rate (float): Initial learning rate<br>        - sigma (float): Initial neighborhood radius (default: max(x, y) / 2)<br>        &quot;&quot;&quot;<br>        self.x = x<br>        self.y = y<br>        self.input_len = input_len<br>        self.learning_rate = learning_rate<br>        self.sigma = sigma if sigma else max(x, y) / 2<br>        self.weights = np.random.rand(x, y, input_len)<br><br>    def _neighborhood(self, winner_coords, i, j, sigma):<br>        &quot;&quot;&quot;<br>        Gaussian neighborhood function.<br>        &quot;&quot;&quot;<br>        dist_sq = (winner_coords[0] - i) ** 2 + (winner_coords[1] - j) ** 2<br>        return np.exp(-dist_sq / (2 * sigma ** 2))<br><br>    def winner(self, x):<br>        &quot;&quot;&quot;<br>        Find the Best Matching Unit (BMU) for a given input.<br>        &quot;&quot;&quot;<br>        distances = np.linalg.norm(self.weights - x, axis=2)<br>        return np.unravel_index(np.argmin(distances), (self.x, self.y))<br><br>    def update(self, x, t, max_iter):<br>        &quot;&quot;&quot;<br>        Update the SOM weights with input vector `x` at time `t`.<br>        &quot;&quot;&quot;<br>        lr = self.learning_rate * np.exp(-t / max_iter)<br>        sigma = self.sigma * np.exp(-t / max_iter)<br>        winner_coords = self.winner(x)<br><br>        for i in range(self.x):<br>            for j in range(self.y):<br>                h = self._neighborhood(winner_coords, i, j, sigma)<br>                self.weights[i, j] += h * lr * (x - self.weights[i, j])<br>        <br>        return winner_coords  # Return BMU for display<br><br><br># === Example Usage ===<br>if __name__ == &quot;__main__&quot;:<br>    np.random.seed(42)  # for reproducibility<br><br>    # Initialize SOM<br>    som = DynamicSOM(x=5, y=5, input_len=3, learning_rate=0.5)<br><br>    # Simulated input data: 50 points with 3 features each<br>    data = np.random.rand(50, 3)<br><br>    max_iter = 50<br>    print(&quot;Training Dynamic SOM...\n&quot;)<br>    for t, x in enumerate(data):<br>        bmu = som.update(x, t, max_iter)<br>        print(f&quot;Time Step {t + 1:02d} - Input: {np.round(x, 2)} - BMU: {bmu}&quot;)<br>       </pre><h3><strong>What are SOMs ?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*tVWly85ODmN7RBA6uqzCSw.gif" /><figcaption>A GIF to simulate Self Organizing Maps using Matplotlib and Plotly</figcaption></figure><p>Static Self-Organizing Maps (SOMs) are trained once and then frozen, making them ill-suited for environments where data evolves continuously — such as financial markets. In contrast, <strong>Dynamic SOMs</strong> are designed to adapt in real-time, allowing them to detect emerging patterns, structural changes, and rare anomalies as they happen.</p><p>Here are the core mechanisms that make SOMs dynamic:</p><h4>1. <strong>Online Updates</strong></h4><p>Dynamic SOMs update their weight vectors incrementally with each incoming data point rather than retraining from scratch. This makes them highly suitable for <strong>streaming financial data</strong>, where waiting for batch retraining would delay critical insights.</p><ul><li><strong>Example:</strong> Each day’s liquidity ratio, deposit outflow, or bond valuation is used to adjust the SOM grid.</li><li><strong>Advantage:</strong> Continuous learning keeps the SOM aligned with the latest market conditions.</li></ul><h4>2. <strong>Decay Functions for Learning and Neighborhood Radius</strong></h4><p>To avoid overfitting to short-term noise, dynamic SOMs employ <strong>decay functions</strong> for the learning rate η(t)\eta(t)η(t) and neighborhood radius σ(t)\sigma(t)σ(t). These functions reduce the magnitude and spread of updates over time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*KLunEaLL_41ENzdOfBoNfA.png" /></figure><ul><li><strong>τ\tauτ:</strong> Time constant determining decay speed</li><li><strong>Effect:</strong> Recent data has a stronger influence, while historical patterns gradually fade unless reinforced.</li></ul><h4>3. <strong>Concept Drift Adaptation</strong></h4><p>Financial systems are inherently non-stationary; trends that held true yesterday might not apply tomorrow. Dynamic SOMs can <strong>adapt to concept drift</strong> by:</p><ul><li>Continuously re-mapping incoming data</li><li>Detecting when clusters shift (e.g., typical liquidity profiles change)</li><li>Re-weighting neuron vectors to reflect new realities</li></ul><p>This means the SOM remains <strong>sensitive to structural changes</strong>, such as those caused by interest rate shifts, new regulations, or geopolitical disruptions.</p><h3>Real-World Scenario: Central Bank Policy Shock</h3><p><strong>Context:</strong><br> You’re using a dynamic SOM to monitor the daily liquidity position of a commercial bank. One day, the central bank unexpectedly raises interest rates by 100 basis points to combat inflation.</p><p><strong>What Happens Next?</strong></p><ul><li><strong>Depositor Behavior:</strong> Customers begin rapidly withdrawing funds, concerned about market volatility.</li><li><strong>Liquidity Ratio Drops:</strong> The bank’s liquid asset-to-liability ratio deteriorates.</li><li><strong>SOM Response:</strong></li><li>The daily updates push the BMU (Best Matching Unit) to a new location on the grid.</li><li>The SOM starts to cluster these post-rate-hike behaviors separately from earlier data.</li><li><strong>Quantization Error</strong> and <strong>BMU shifts</strong> increase — indicating a deviation from the bank’s previous operational baseline.</li><li><strong>Outcome:</strong><br> The SOM triggers an <strong>anomaly alert</strong>, flagging this emerging liquidity stress well before it might breach regulatory thresholds or spark a crisis.</li></ul><h4><strong>So, How does SOMs spot anomalies ?</strong></h4><p>Anomalies are things that <strong>don’t fit</strong> — like spotting someone wearing a winter coat on a hot summer day. SOMs detect these oddballs in three smart ways:</p><h3>1. Quantization Error — “How Well Do I Know You?”</h3><p>Every new data point is assigned a “best match” on the SOM — called the <strong>Best Matching Unit (BMU)</strong>. Then we ask:</p><blockquote>“How far is this input from its BMU?”</blockquote><p>This distance is called the <strong>Quantization Error (QE)</strong>.</p><ul><li>If the QE is <strong>low</strong>, the input is well-represented — it’s “normal”.</li><li>If QE is <strong>high</strong>, it’s unfamiliar — <strong>a red flag!</strong></li></ul><p><strong>Analogy</strong>: You meet someone at a party. If they’re similar to people you know, you feel comfortable. But if they’re unlike anyone you’ve met, you feel uncertain — that’s high QE.</p><h4>Mathematical Formulation :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*xCLpJXkdz46xFw5i_G8Nwg.png" /></figure><h3>2. Topographic Error — “Should You Be Neighbors?”</h3><p>SOMs are good at putting <strong>similar things next to each other</strong> on the map.</p><p>So when a new input is <strong>so strange</strong> that its <strong>top two closest BMUs aren’t even neighbors</strong>, that breaks the map’s structure — we call this <strong>Topographic Error (TE)</strong>.</p><ul><li>High TE = the input doesn’t fit neatly anywhere on the map.</li></ul><p><strong>Analogy</strong>: It’s like someone showing up at a wedding and behaving in a way that doesn’t match any group of guests. Weird, right?</p><h4><strong>Mathematical Formulation :</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*KprcduzHJuQVXvlCMd6EoA.png" /></figure><h3>3. BMU Frequency — “You’ve Never Been Here Before”</h3><p>Every time the SOM matches a data point to a neuron, it records which neuron it was.</p><ul><li>Some neurons get activated often — the <strong>hotspots</strong> — that’s normal behavior.</li><li>Others are rarely (or never) used — the <strong>cold spots</strong>.</li></ul><p>When a data point lands in a <strong>cold spot</strong>, it might be a brand-new pattern — or an <strong>anomaly</strong>.</p><p><strong>Analogy</strong>: You notice someone walking into a corner of your shop that no one ever visits. Suspicious? Maybe.</p><h3>Putting It All Together — How SOM Detects Anomalies</h3><p>So what happens when a <strong>new data point arrives</strong>?</p><ol><li>The SOM finds the BMU (the neuron it fits best).</li><li>It calculates:</li></ol><ul><li><strong>Quantization Error</strong>: How far is this point from its BMU?</li><li><strong>Topographic Error</strong>: Are the BMU and its runner-up close to each other?</li></ul><p><strong>BMU Frequency</strong>: Is this BMU rarely used?</p><ol><li>The SOM <strong>flags</strong> the point as an <strong>anomaly</strong> if:</li></ol><ul><li>The QE is <strong>above a certain threshold</strong></li><li>OR the TE is <strong>high</strong></li><li>OR the neuron is from a <strong>cold zone</strong></li></ul><h3>Example: Bank Transaction Monitoring</h3><p>Let’s say a bank is using SOMs to monitor <strong>daily liquidity patterns</strong>.</p><ul><li>Most days follow known behavior: deposits, withdrawals, transfers.</li><li>Suddenly, due to a central bank policy change, <strong>cash withdrawals spike</strong>.</li></ul><p>The SOM:</p><ul><li>Sees a <strong>high QE</strong> (this behavior doesn’t match the usual patterns).</li><li>Might detect a <strong>high TE</strong> (this behavior doesn’t fit neatly anywhere).</li><li>Notes that this BMU is in a rarely activated region (a cold spot).</li></ul><p>Boom. SOM <strong>raises an alert</strong>.</p><h3>Why Is This So Powerful?</h3><ul><li>SOMs don’t need labels like “fraud” or “normal”.</li><li>They can handle <strong>new behaviors</strong> and <strong>evolve over time</strong>.</li><li>They make <strong>data visualization</strong> easy: you can <strong>see where things go wrong</strong>.</li></ul><h3>Use Case: Could SOMs Have Helped Predict the SVB Collapse?</h3><h3>📜 Quick Recap: What Happened to SVB?</h3><p>Silicon Valley Bank was a key player in the startup ecosystem. But in early 2023, it collapsed almost overnight. Why?</p><ul><li>The bank had heavily invested in <strong>long-term bonds</strong>.</li><li>When the <strong>Fed hiked interest rates</strong>, those bonds <strong>lost value</strong>.</li><li>Meanwhile, <strong>startups</strong> (who were SVB’s primary clients) started <strong>withdrawing more money</strong> to survive the funding winter.</li><li>To cover these withdrawals, SVB sold bonds at a loss, sparking panic.</li><li>Within <strong>48 hours</strong>, it experienced a modern-day bank run.</li></ul><p>In short: a <strong>liquidity crisis</strong>, worsened by <strong>interest rate shocks</strong> and <strong>withdrawal behavior</strong> shifting rapidly.</p><h3>How SOMs Could Have Helped</h3><p>Imagine if SVB had a <strong>Dynamic SOM</strong> constantly watching <strong>daily liquidity, customer withdrawals, and deposit patterns</strong>.</p><p>Here’s how it might have gone down:</p><h3>1. Learning Normal Patterns Over Time</h3><p>The SOM would have quietly watched data for months — learning the <strong>“normal” rhythm</strong> of SVB:</p><ul><li>How much money flows in and out on a typical day</li><li>How startup customers behave</li><li>Typical reaction to small rate hikes</li></ul><p>This becomes its <strong>mental map</strong>.</p><h3>Early Warning with Quantization Error (QE)</h3><p>Suddenly, customers start <strong>pulling out larger amounts</strong> than usual.</p><p>For the SOM, this is like someone shouting in a quiet library — the QE (quantization error) <strong>spikes</strong>:</p><blockquote>“This behavior doesn’t match what I’ve seen before!”</blockquote><p>A human might still say “It’s just a few customers panicking.”<br> But the SOM says:</p><blockquote>“It’s <strong>systematically different</strong> from the past. Something’s off.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*pgdaUOKsRlZGgbs6y_qF2Q.png" /><figcaption>Figure showing significant error after 100th day</figcaption></figure><h3>3. Cold Zone Activation (Rare BMU Zones)</h3><p>The SOM’s neurons that <strong>rarely light up</strong> suddenly start triggering:</p><ul><li>These neurons represent behaviors like <strong>mass withdrawals</strong> or <strong>institutional panic</strong>, learned faintly in the past (maybe from 2008-like data).</li><li>These are <strong>not normal</strong>.</li></ul><p>It’s like a smoke detector going off in a usually quiet room.</p><h3>4. Topographic Error Rises (Behavior Is Fragmenting)</h3><p>Even the <strong>second-closest neurons</strong> to incoming data are <strong>far apart</strong> on the map.</p><p>That tells us:</p><blockquote>“There’s <strong>no clear cluster</strong> this behavior belongs to. It’s uncharted territory.”</blockquote><p>This pattern of <strong>fragmentation</strong> is a hallmark of stress and instability.</p><h3>5. Real-Time Alerts to Decision Makers</h3><p>If SVB had this SOM in production, it could have:</p><ul><li>Triggered <strong>real-time dashboards</strong> for the risk team</li><li>Flagged <strong>rising QE and TE trends</strong></li><li>Visualized how recent data is moving into <strong>abnormal map zones</strong></li></ul><p>Maybe — just maybe — this would’ve given them <strong>days or weeks</strong> to act more decisively, rather than hours during a social-media-fueled bank run.</p><h3>How You Could Build This in Practice</h3><p>Here’s how a modern bank or fintech could implement it:</p><ol><li><strong>Collect</strong> daily data: deposits, withdrawals, loan demands, interest rates.</li><li>Train a <strong>Dynamic SOM</strong> (online updating SOM) on normal data over months.</li><li>Monitor in real-time:</li></ol><ul><li><strong>Quantization Error</strong> spikes</li><li><strong>Cold spot</strong> neuron activations</li><li><strong>Topographic Error</strong> and BMU movement</li></ul><ol><li>Set <strong>thresholds</strong> and <strong>alerting systems</strong> for anomalies.</li><li>Use a <strong>heatmap or dashboard</strong> to visualize danger zones.</li></ol><h3>Final Thought: SOMs as Early Warning Systems</h3><p>SOMs don’t replace financial analysis — but they <strong>augment intuition with pattern memory</strong>.</p><p>They <strong>don’t forget the past</strong>, and they <strong>don’t panic</strong> under pressure.<br> Instead, they calmly say:</p><blockquote>“I’ve seen thousands of behaviors. This one doesn’t fit. Let’s look into it.”</blockquote><p>That kind of <strong>quiet intelligence</strong> might be just what banks need in a noisy world.</p><h3>Let us simulate a python code to visualize what this Code Does:</h3><ul><li>Simulates <strong>normal banking behavior</strong> (withdrawals, deposits, interest rates)</li><li>Introduces <strong>anomalous behavior</strong> to mimic an SVB-like collapse</li><li>Trains the SOM on normal data</li><li>Detects anomalies using:</li><li><strong>Quantization Error (QE)</strong></li><li><strong>Distance from BMU</strong></li><li>Flags anomalies if their QE is significantly above average</li></ul><h3>Python Code :</h3><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from minisom import MiniSom<br>from sklearn.preprocessing import MinMaxScaler<br><br>def simulate_bank_data(normal_days=100, anomalous_days=20, seed=42):<br>    &quot;&quot;&quot;<br>    Simulates banking behavior data with both normal and anomalous patterns.<br>    <br>    Parameters:<br>        normal_days (int): Number of days with normal banking activity.<br>        anomalous_days (int): Number of days with SVB-style anomalies.<br>        seed (int): Random seed for reproducibility.<br>        <br>    Returns:<br>        np.ndarray: Combined dataset of normal and anomalous banking activities.<br>    &quot;&quot;&quot;<br>    np.random.seed(seed)<br><br>    # Simulate normal banking behavior<br>    normal_data = np.column_stack([<br>        np.random.normal(100, 10, normal_days),   # Withdrawals<br>        np.random.normal(110, 8, normal_days),    # Deposits<br>        np.random.normal(1.5, 0.1, normal_days)   # Interest rate<br>    ])<br><br>    # Simulate anomalous behavior mimicking SVB collapse<br>    anomaly_data = np.column_stack([<br>        np.random.normal(200, 15, anomalous_days),  # Spike in withdrawals<br>        np.random.normal(80, 10, anomalous_days),   # Drop in deposits<br>        np.random.normal(3.0, 0.2, anomalous_days)  # Surge in interest rates<br>    ])<br><br>    # Combine and return the dataset<br>    return np.vstack([normal_data, anomaly_data])<br><br>def normalize_data(data):<br>    &quot;&quot;&quot;<br>    Normalizes the data using Min-Max scaling.<br>    <br>    Parameters:<br>        data (np.ndarray): Raw input data.<br>        <br>    Returns:<br>        np.ndarray: Normalized data.<br>    &quot;&quot;&quot;<br>    scaler = MinMaxScaler()<br>    return scaler.fit_transform(data)<br><br>def train_som(data, input_len, x=5, y=5, sigma=0.5, learning_rate=0.5, iterations=1000):<br>    &quot;&quot;&quot;<br>    Trains a Self-Organizing Map (SOM) using given input data.<br>    <br>    Parameters:<br>        data (np.ndarray): Training data.<br>        input_len (int): Number of input features.<br>        x, y (int): Grid size of the SOM.<br>        sigma (float): Spread of the neighborhood function.<br>        learning_rate (float): Initial learning rate.<br>        iterations (int): Number of iterations for training.<br>        <br>    Returns:<br>        MiniSom: Trained SOM object.<br>    &quot;&quot;&quot;<br>    som = MiniSom(x=x, y=y, input_len=input_len, sigma=sigma, learning_rate=learning_rate)<br>    som.random_weights_init(data)<br>    som.train_random(data, iterations)<br>    return som<br><br>def compute_quantization_errors(som, data):<br>    &quot;&quot;&quot;<br>    Computes quantization error (QE) for each data point in the dataset.<br>    <br>    Parameters:<br>        som (MiniSom): Trained SOM.<br>        data (np.ndarray): Dataset to evaluate.<br>        <br>    Returns:<br>        list: QE values for each data point.<br>    &quot;&quot;&quot;<br>    return [np.linalg.norm(x - som.get_weights()[som.winner(x)]) for x in data]<br><br>def detect_anomalies(qe, normal_cutoff):<br>    &quot;&quot;&quot;<br>    Identifies anomalies based on QE thresholding.<br>    <br>    Parameters:<br>        qe (list): Quantization errors for data points.<br>        normal_cutoff (int): Number of initial days considered as normal.<br>        <br>    Returns:<br>        list: Indices of data points flagged as anomalies.<br>    &quot;&quot;&quot;<br>    threshold = np.mean(qe[:normal_cutoff]) + 2 * np.std(qe[:normal_cutoff])<br>    anomalies = [i for i, error in enumerate(qe) if error &gt; threshold]<br>    return anomalies, threshold<br><br>def plot_results(qe, anomalies, normal_cutoff, threshold):<br>    &quot;&quot;&quot;<br>    Plots the quantization error over time and highlights anomalies.<br>    <br>    Parameters:<br>        qe (list): Quantization errors for data points.<br>        anomalies (list): Indices of anomalies.<br>        normal_cutoff (int): Index after which anomalies begin.<br>        threshold (float): Anomaly detection threshold.<br>    &quot;&quot;&quot;<br>    plt.figure(figsize=(12, 6))<br>    plt.plot(qe, label=&#39;Quantization Error (QE)&#39;)<br>    plt.axvline(x=normal_cutoff, color=&#39;red&#39;, linestyle=&#39;--&#39;, label=&#39;SVB Collapse Begins&#39;)<br>    plt.axhline(y=threshold, color=&#39;orange&#39;, linestyle=&#39;--&#39;, label=&#39;Anomaly Threshold&#39;)<br>    plt.scatter(anomalies, [qe[i] for i in anomalies], color=&#39;red&#39;, label=&#39;Anomalies&#39;, zorder=5)<br>    plt.xlabel(&#39;Day&#39;)<br>    plt.ylabel(&#39;Quantization Error&#39;)<br>    plt.title(&#39;Anomaly Detection using SOM (SVB Collapse Simulation)&#39;)<br>    plt.legend()<br>    plt.grid(True)<br>    plt.tight_layout()<br>    plt.show()<br><br>def main():<br>    &quot;&quot;&quot;<br>    Main function to run the SOM anomaly detection pipeline.<br>    &quot;&quot;&quot;<br>    # Step 1: Simulate and normalize data<br>    normal_days = 100<br>    anomaly_days = 20<br>    raw_data = simulate_bank_data(normal_days, anomaly_days)<br>    data_scaled = normalize_data(raw_data)<br><br>    # Step 2: Train SOM on normal data<br>    som = train_som(data_scaled[:normal_days], input_len=3)<br><br>    # Step 3: Calculate quantization errors and detect anomalies<br>    qe = compute_quantization_errors(som, data_scaled)<br>    anomalies, threshold = detect_anomalies(qe, normal_days)<br><br>    # Step 4: Visualize results<br>    plot_results(qe, anomalies, normal_days, threshold)<br><br>    # Step 5: Output anomaly days<br>    print(&quot;Anomalies detected on days (0-indexed):&quot;, anomalies)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>Let us visualize the output :</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quPiIXWHf0ii9xCIVRqVaQ.png" /></figure><p><strong><em>Anomaly detected on days (0-indexed): [6, 9, 25, 35, 56, 67, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119]</em></strong></p><h3>Real-World Applications of Self-Organizing Maps</h3><p>Self-Organizing Maps aren’t just academic toys — they’re used in a variety of industries to bring order to chaos in high-dimensional data. Here’s how they shine in the real world:</p><h4>1. Financial Anomaly Detection</h4><p>Banks and fintech companies use SOMs to monitor transactions. When customer behavior suddenly deviates from past patterns (like unusual withdrawals or spending spikes), SOMs can detect it in near real-time — even if the change is subtle.</p><h4>2. Customer Segmentation</h4><p>In marketing, SOMs help visualize and group customers based on demographics, behavior, or preferences — ideal for targeted campaigns or churn prediction.</p><h4>3. Healthcare and Bioinformatics</h4><p>Doctors and researchers use SOMs to visualize patterns in genetic data, patient records, or disease symptoms, helping in diagnosis or treatment recommendation.</p><h4>4. Cybersecurity</h4><p>SOMs are used in intrusion detection systems (IDS) to flag network behavior that deviates from the “normal” map — detecting malware, DDOS, or insider threats.</p><h4>5. Supply Chain Monitoring</h4><p>A sudden disruption in deliveries or costs can be picked up by SOMs analyzing patterns in supplier or logistics data over time.</p><h4>6. Stock Market Behavior</h4><p>By feeding in daily metrics like volatility, volume, and price movement, SOMs can track how stock behavior clusters change — helping detect bubbles or crashes (like the <strong>SVB collapse</strong> we discussed).</p><h3>Final Thoughts: Why SOMs Matter Today</h3><p>In a world overflowing with unstructured and high-dimensional data, Self-Organizing Maps give us <strong>a powerful lens to “see” and make sense of hidden patterns</strong> — even before they become obvious.</p><p>And with <strong>dynamic SOMs</strong>, the maps evolve in real-time, adapting to shifting trends and concept drifts, making them ideal for live dashboards, streaming data applications, or early warning systems.</p><p><strong>Whether you’re a data scientist, domain expert, or just curious</strong>, SOMs offer a unique blend of:</p><ul><li>Dimensionality reduction</li><li>Unsupervised learning</li><li>And intuitive visualization.</li></ul><p>So the next time you’re faced with complex data that seems overwhelming, remember — SOMs might just help you <em>let the data organize itself</em>.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35ebcd1ca23b" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/dynamic-map-based-learning-with-soms-for-real-time-anomaly-detection-in-finance-35ebcd1ca23b">Dynamic Map-Based Learning with SOMs for Real-Time Anomaly Detection in Finance</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond ARMA: Unveiling Mamba, GRU, KAN & GNN for the Future of Time Series Forecasting]]></title>
            <link>https://medium.com/@23subhasmukherjee/beyond-arma-unveiling-mamba-gru-kan-gnn-for-the-future-of-time-series-forecasting-92dd48691060?source=rss-34a20cdf5e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/92dd48691060</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Subhasmukherjee]]></dc:creator>
            <pubDate>Wed, 30 Apr 2025 18:13:44 GMT</pubDate>
            <atom:updated>2025-04-30T18:13:44.001Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What even is Time Series ? </strong><br>From predicting stock prices and consumption of energy to anticipating patient vitals and weather forecasting across industries time series analysis plays a crucial role in fueling critical decisions. For decades, the ARMA model provided reliable baselines — but in today’s data-driven society, linear assumptions and short term simple memory just do not cut it.</p><p>Let me introduce a new breed of models —<strong> GRU</strong> (A memory efficient deep learner build over LSTM),<strong>GNN </strong>which capture relational dependencies across multiple time series data, <strong>KAN’s</strong> which introduces smooth functional mappings and <strong>Mamba </strong>which is a state-space disruptor build for long-term precisions. This blog will explore all these state-of-the-art models and how they stack up with modern problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPt4oAHWiuoIBQguoT12ow.gif" /></figure><h3>Traditional Time Series Model: ARMA</h3><p>Before diving in to complex deep learning architectures, let us try to understand the foundation lead by previous statistical models — mainly the ARMA model. Full form meaning <strong>Auto Regressive Moving Average, ARMA </strong>has long been the cornerstone for time-series forecasting especially finance, economics and weather patterns.</p><p><strong>What is ARMA ? <br></strong>This model combines two basic components : <br>1. Autoregressive (AR) part : This captures the overall previous trend of a time series data in order to predict today’s fluctuations or future long-term trend. For example : If someone wants to predict today’s market fluctuations based on learned previous data by the model. <br>2. Moving Average (MA) part : This models the prediction of past residuals and the main motive behind MA is to smooth-out volatility and fluctuation mainly focusing on averaging noise and randomness over a long period of time.</p><p>Mathematically the ARMA model can be represented as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*S6tNoxwwHA9iy9fMQBQCng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*wMe5zcKHVCiko6sEkuuPQw.png" /></figure><h3>When ARMA Works Well</h3><p>ARMA is highly effective when:</p><ul><li>The time series is <strong>stationary</strong> (i.e., its statistical properties like mean and variance do not change over time).</li><li>The patterns are <strong>linear and short-term dependent</strong>.</li><li>Interpretability becomes important when dealing with time series analysis and as being a simple intuitive model it provides this advantage.</li></ul><p>It’s fast, computationally efficient, and easily interpretable — traits that still make it useful for simple and well-behaved datasets.</p><h3>Limitations of ARMA</h3><p>However, ARMA starts to show its age in the face of modern forecasting challenges:</p><ul><li>It struggles with <strong>non-stationary</strong> or <strong>nonlinear data </strong>and as most data in the real world belong to these category, the model pose a problem.</li><li>It cannot naturally model <strong>long-term dependencies which means it does not take account of too much historical data when making predictions</strong>.</li><li>It doesn’t scale well with <strong>multivariate time series</strong> or complex relational data.</li><li>Manual feature engineering and <strong>stationarity assumptions</strong> often limit its flexibility and become highly prone to wrong predictions.</li></ul><h3>Why Move Beyond ARMA?</h3><p>The complexity of today’s data demands more powerful, flexible models. With the sudden surge of deep learning and neural architectures, forecasting has advanced much more than just understanding temporal lags — it now requires capturing <strong>nonlinear trends</strong>, <strong>external factors</strong>, <strong>relationships across multiple signals</strong>, and <strong>long-term memory</strong>.</p><p>While ARMA still holds value in certain analytical contexts, it often serves better as a <strong>baseline</strong> than a best-in-class solution.</p><h3><strong>Modern Deep Learning Models</strong></h3><p>As real-world time series data is becoming very complex, deep learning models become key tools for capturing nonlinear patterns, long-term dependencies, and relationships across multiple signals. In this section, we’ll explore four modern approaches — <strong>GRU</strong>, <strong>GNN</strong>, <strong>KAN</strong>, and <strong>Mamba</strong> — each representing a unique evolution in time series forecasting.</p><p><strong>Gated Recurrent Unit (GRU): </strong><br>The GRU is a type of Recurrent Neural Network which was introduced to solve the <strong>Vanishing Gradient</strong> problem and efficiently capture temporal dependencies without the immense complexity of gating mechanisms introduced in LSTMS. In simple terms, it works much like LSTMs but is much faster with fewer gates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*6FeaWphrXTnUO56in5AqzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*7nfAYZUDnwhuyXdUZNCmtg.png" /></figure><p><strong>Graph Neural Networks (GNN):</strong> <br>When dealing with <strong>multiple interrelated time series</strong>, such as sensors in a network or correlated stocks, <strong>GNNs</strong> offer a powerful way to model <strong>spatial-temporal dependencies</strong> using graph structures.</p><p>Key Idea:<br>Each time series (node) is influenced by its neighbors through <strong>message passing</strong>. This message passing process is akin to nodes in a graph exchanging messages or signals, hence the name “Neural Message Passing.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*al3CKnLkdC4UfimUYqrHtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*UTwy5AJFvIeN7gw0E5Nu6Q.jpeg" /></figure><p><strong>Kolmogorov–Arnold Networks (KAN):</strong> <br><strong>KANs</strong> represent a new class of neural networks inspired by the <strong>Kolmogorov–Arnold theorem</strong>, which states that any multivariate function can be decomposed into univariate functions for further processing where it first takes the input as a parametric function then we perform the <strong>inner sum of the input variables.</strong><br>Furthermore the intermediate variables are again passed through a <strong>parameterized function</strong> and finally perform the<strong> outer sum</strong> to get the output.</p><p>Key Idea:<br>Replace traditional neurons with smooth functional transformations:</p><p>No fixed activations (like ReLU); instead, learn continuous piecewise-polynomial functions.</p><p>While the mathematical formulation may vary, conceptually it could be :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*s10J-waQrBHLB2WyNJx0pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CdNVV5yC9jgottNwmbhryA.png" /></figure><p><strong>Mamba :</strong> <br><strong>Mamba</strong> is a breakthrough model based on <strong>state-space architectures</strong>, designed to handle <strong>very long sequences</strong> with lower complexity than Transformers. <br>To enable handling long data sequences, Mamba incorporates the Structured State Space Sequence model (S4). S4 can effectively and efficiently model long dependencies by combining continuous-time, <a href="https://en.wikipedia.org/wiki/Recurrent_neural_network">recurrent</a>, and <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">convolutional</a> models. These enable it to handle irregularly sampled data, unbounded context, and remain computationally efficient during training and inferencing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*wJ3oB-CdAXDmPwtHdsa1lA.png" /></figure><p>Mamba shines in tasks where capturing <strong>global context</strong> over long periods is essential — such as <strong>climate forecasting</strong>, <strong>health monitoring</strong>, and <strong>document-level sequence modeling</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELCPzqbKuK2A_XFVD5m2tA.png" /></figure><h3>Comparative Analysis: Model Strengths &amp; Use Cases :</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*oXv2I08uScM97oz430_nLA.png" /></figure><h4>Key Insights :</h4><ul><li><strong>ARMA</strong> is reliable for <strong>simple, linear</strong> models but fails with nonlinear or multivariate data as we have discussed earlier.</li><li><strong>GRU</strong> balances <strong>efficiency and memory</strong>, suitable for a wide range of temporal tasks and is a better version of LSTM.</li><li><strong>GNNs</strong> shine where <strong>relationships between series</strong> matter — especially in <strong>networked systems meaning it excels for multiple time-series data</strong>.</li><li><strong>KAN</strong> is a bridge between <strong>symbolic and neural models</strong>, offering high <strong>functional clarity and computational speed</strong>.</li><li><strong>Mamba</strong> is state-of-the-art for <strong>extremely long sequences</strong>, offering linear-time inference without sacrificing context.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*t5zoPXypQfkCBg2XB5VdaA.png" /></figure><h3>Interesting &amp; Engaging Facts About Time Series Models</h3><ol><li><strong>The First Time Series Forecasting Model Was Invented in 1927</strong><br> The foundational AR (AutoRegressive) model, which ARMA builds upon, dates back almost a century — proof that time series modeling has deep roots in statistical science.</li><li><strong>GRU vs LSTM: Who Wins?</strong><br> While LSTMs are more famous, <strong>GRUs</strong> often outperform them in real-world tasks with fewer parameters and faster training — like a leaner athlete with the same endurance.</li><li><strong>GNNs Can Forecast Traffic Jams Before They Happen</strong><br> Graph Neural Networks are being used in smart cities to <strong>predict traffic congestion hours ahead</strong> by modeling roads as interconnected nodes. Think Google Maps, but smarter.</li><li><strong>KANs Learn Functions Like Calculators</strong><br> Kolmogorov–Arnold Networks (KANs) <strong>learn functions directly</strong> rather than patterns. That makes them not just predictors but potential equation discoverers — giving AI a more math-like brain.</li><li><strong>Mamba Was Named After a Snake, But Thinks Like a Brain</strong><br> The <strong>Mamba model</strong>, based on selective state-space modeling, combines the speed of convolution with the memory of recurrence — and can process thousands of tokens with <strong>linear efficiency</strong>.</li><li><strong>Recurrence Is Out, State-Space Is In?</strong><br> Mamba and S4 models suggest a <strong>paradigm shift in deep learning</strong>: moving away from RNNs to more efficient, state-aware architectures. It’s like replacing memory with intuition.</li><li><strong>90% of the World’s Data Is Time Series</strong><br> From <strong>IoT sensors</strong>, <strong>stock prices</strong>, <strong>social media activity</strong>, to <strong>weather data</strong>, most real-world signals are time-dependent — making time series forecasting one of the most impactful AI domains today.</li><li><strong>NASA Uses Hybrid Models</strong><br> NASA combines traditional ARMA models with neural networks to forecast <strong>space weather and satellite trajectory corrections</strong> — proving that sometimes, the best solution is a team.</li></ol><h3>Conclusion: The Past Meets the Future of Time Series</h3><p>From the elegant simplicity of <strong>ARMA</strong> to the cutting-edge dynamics of <strong>Mamba</strong> and <strong>KAN</strong>, time series forecasting has evolved into a rich fusion of <strong>statistical wisdom and neural innovation</strong>. Each model we’ve explored has its own superpower — be it interpretability, memory, scalability, or structural awareness.</p><p>But here’s the twist: there’s no silver bullet.</p><blockquote>The real magic happens when we understand <strong>which model fits which problem</strong>, and dare to <strong>combine their strengths</strong>.</blockquote><p>As we move toward an era dominated by <strong>multivariate, multimodal, and real-time predictions</strong>, the race won’t just be about accuracy — it’ll be about <strong>efficiency, and adaptability</strong>.</p><p>So whether you’re modeling climate, stock markets, traffic, or the heartbeat of a smart city, the tools are here. The challenge is <strong>choosing wisely</strong> — or better yet, <strong>blending boldly</strong>.</p><p>Let the future forecast itself — with a little help from AI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92dd48691060" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CNN features for prompt conditioning — Adding structure to prompting chaos]]></title>
            <link>https://medium.com/@23subhasmukherjee/cnn-features-for-prompt-conditioning-adding-structure-to-prompting-chaos-bf8a51d32ed9?source=rss-34a20cdf5e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8a51d32ed9</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Subhasmukherjee]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 14:46:39 GMT</pubDate>
            <atom:updated>2025-04-13T14:46:39.521Z</atom:updated>
            <content:encoded><![CDATA[<h3>CNN features for prompt conditioning — Adding structure to prompting chaos</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hdpmg9ICPDcB66uTteKJDA.png" /></figure><p><strong>Why vague prompting when you can structure it ?</strong> <br>In the recent age of Gen AI, <em>prompts </em>had significantly gained popularity — a single line of text which can generate artwork, compose music or write poems. But prompts alone ? — They are basic, inconsistent and sometimes vague too. Now envisage injecting structure into it. That’s where CNN features comes to the picture. <br>Have you ever wondered how in recent trends Generative models are able to generate ‘Ghibli-style images’ from just a phrase and a picture ? The magic lies in the functionality of convolutional neural networks (CNNs) extracting rich spatial and semantic features that serve as <em>conditioners</em> — guiding generation at every step.<br>This article dives into how CNN-extracted features are used to <strong>guide, shape, and condition generative models</strong>, from image translation to text-to-image alignment, and how you can mathematically and intuitively make sense of everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNxUCF4HrVpEqiPE2fG2xw.gif" /></figure><p><strong>Why we use CNN for Conditioning ? </strong><br>CNNs specialize in extracting local hierarchical and spatial features from images — from edges to textures to artifacts. <br>These features can be : <br>1. Fused with text embeddings <br>2. Used as style references<br>3. Injected in to architecture of Generative models like GANs, VAEs and Diffusion models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdSCqnksF0JFuArDyoQOug.gif" /></figure><p><strong>Mathematical substratum for Prompt Conditioning :</strong><br>Lets start with a Generative model <em>G </em>which initially takes a latent vector <em>z</em> and generates an output . With the help of conditioning, we can incorporate external variables<em> c. Typically derived from an </em><strong><em>CNN :</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/90/1*I38PBtfYpI-7CpySZOx0fw.png" /></figure><p>Here if <em>c</em> is the output from a CNN then :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*Adf65nhbzukUzSdLYKNscg.png" /></figure><p>Now the model generation becomes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/1*PDO1L2A4GiRVXE30EhEMbA.png" /></figure><p>In diffusion models, the denoising process is guided step-by-step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*C7TiVyP2yj4I6piRjNyESg.png" /></figure><p>This effectively aligns generation with spatial or semantic information encoded by the CNN.</p><p><strong>Use Cases : </strong><br>1. Text-Image Alignment</p><ul><li>CNN patches align with text tokens via cross-attention</li><li>Used in CLIP-guided diffusion or cross-modal transformers.</li></ul><p>2. Style Transfer</p><ul><li>Extract <em>style embeddings</em> from CNN feature maps (e.g., Gram matrices):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*AVPHgkWfXfk-IlLVZDnVhw.png" /></figure><p>Where ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/1*v-WSjPQCBJZNFZTzn1Ou5w.png" /></figure><p>is the feature map.</p><p>3. Layout Conditioning :</p><ul><li>CNN encodes spatial layouts.</li><li>The generator uses these as positional constraints to control object placements.</li></ul><p><strong>Architectures That Use CNN Conditioning</strong></p><p><strong>Style GAN</strong>:</p><ul><li><strong>Core Idea</strong>: It helps to modulate the generator with styles derived from latent codes or CNN-extracted features.</li><li><strong>Conditioning method</strong>: CNNs (e.g., VGG) are used to extract feature maps from a reference image. These are then used to control synthesis at different generator layers via <em>adaptive instance normalization</em> .</li><li><strong>Formula </strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*mZX61D2sG1L37MNlPaYbvA.png" /></figure><p><strong>Use case</strong>: Style transfer, face editing, artistic generation with reference images.</p><p><strong>ControlNet</strong>:</p><ul><li><strong>Core Idea</strong>: Add external control (depth maps, edges, human poses, etc.) to pre-trained diffusion models without retraining the entire network.</li><li><strong>Conditioning method</strong>: A CNN encoder processes the control input (e.g., a Canny edge map), producing intermediate features that are injected into each block of a frozen diffusion model.</li><li><strong>Feature fusion</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*bJwv-qQu_2DkcroIlO9OkQ.png" /></figure><p><strong>Use case</strong>: Conditional generation with structure — sketch-to-image, depth-to-image, pose-to-image.</p><p><strong>Textual Inversion + CNN</strong>:<br> <strong>Core Idea</strong>: CNN encoder-decoder architecture for image-to-image translation (paired data).</p><ul><li><strong>Conditioning method</strong>: The input image is passed through a CNN encoder to extract spatial features. These features directly guide the decoder/generator.</li><li><strong>GAN objective</strong> (simplified):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*xJrtOxXqRKLlTD56PMsdww.png" /></figure><p><strong>Use case</strong>: Map to photo, sketch to image, satellite to street view, segmentation to image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFGrEkWtkR_uhKUGvxTBAQ.png" /></figure><p><strong>Key Insight: Prompt ≠ Conditioning : <br></strong>One must keep this in mind that prompts are just the inputs. On the other hand conditioning is the guidance. CNNs allow these input prompts to gain structure, context and control — turning open-ended generation in to something purposeful.<br>CNNs shine in extracting rich, <strong>localized</strong> and <strong>multi-level</strong> features from visual inputs. This makes them ideal for transforming <strong>conditioning inputs</strong> — such as edges, layouts, depth maps, or reference styles — into something that the generator can <em>meaningfully</em> use.</p><p><strong>Example</strong>:</p><ul><li><strong>Prompt</strong>: “A portrait of a woman in Van Gogh style”</li><li><strong>Conditioning</strong>: A reference image fed through a CNN to extract the painterly brushstroke style.</li></ul><p>Without the CNN-based conditioning, the model may interpret “Van Gogh style” abstractly or inconsistently. With CNN conditioning, we extract actual texture, color palette, and stroke patterns from a Van Gogh painting to guide generation</p><p><strong>Analogy :</strong></p><p>Think of prompts as <strong>wishes</strong>. Think of conditioning as <strong>instructions on how to grant them</strong>.</p><p>You can prompt “Make me a cake.”<br> But conditioning tells the model:</p><ul><li>It should be a chocolate cake (semantic control)</li><li>In the shape of a heart (spatial control)</li><li>Styled like a 1950s retro diner (style control)</li></ul><h3>Citations</h3><ol><li>Ramesh et al. (2022), <em>Hierarchical Text-Conditional Image Generation with CLIP Latents</em>, <a href="https://arxiv.org/abs/2204.06125">arXiv:2204.06125</a></li><li>Zhang et al. (2016), <em>Image Style Transfer Using Convolutional Neural Networks</em>, <a href="https://arxiv.org/abs/1508.06576">CVPR</a></li><li>Zhang &amp; Agrawala (2023), <em>Adding Conditional Control to Diffusion Models via CNNs</em>, <a href="https://arxiv.org/abs/2302.05543">arXiv</a></li><li>Karnewar et al. (2023), <em>ControlNet: Adding Conditional Controls to Text-to-Image Diffusion Models</em>, <a href="https://github.com/lllyasviel/ControlNet">GitHub</a></li><li>Isola et al. (2017), <em>Image-to-Image Translation with Conditional Adversarial Networks</em>, <a href="https://arxiv.org/abs/1611.07004">CVPR</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8a51d32ed9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond a single direction : Bi-RNNs transform speech recognition]]></title>
            <link>https://medium.com/@23subhasmukherjee/beyond-a-single-direction-bi-rnns-transform-speech-recognition-5ddb3dc43f66?source=rss-34a20cdf5e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ddb3dc43f66</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <dc:creator><![CDATA[Subhasmukherjee]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 06:33:48 GMT</pubDate>
            <atom:updated>2025-03-27T06:33:48.696Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Beyond a single direction : Bi-RNNs transform speech recognition</strong></blockquote><p>Have you ever wondered how virtual assistants like Siri and Google Assistant understand our words so precisely. Well, it’s not rocket science rather the secret resides within<strong> The Bi-directional Recurrent Neural Network(Bi-RNNs)</strong> — an advanced RNN architecture which process speech from both the forward and backward directions. Unlike traditional models which rely only on the past contexts, Bi-RNNs capture full context making it accurate for speech recognition. <br>In this blog, we will deep dive in to how Bi-RNNs work, their mathematical foundation and how they have revolutionized speech recognition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*pax4V7B-DYyQIUUY_DWs5Q.png" /><figcaption>A general structure of Bi-RNN taken from the paper Bidirectional Recurrent Neural Networks Mike Schuster and Kuldip K. P., Member, IEEE</figcaption></figure><p><strong>What exactly are Bi-RNNs ? <br></strong>Bidirectional Recurrent Neural Networks are a sophistical extension of the traditional RNNs architecture. The main motive behind the innovation was that traditional RNNs despite having a memory input struggled with vanishing gradient problems for significantly long dependencies. <br>Bi-RNN mitigate this issue by processing input sequence in opposite directions : <strong><br>1. Forward Layer : </strong>This layer process the sequence from beginning to end. <strong><br>2. Backward Layer : </strong>This layer process the sequence from end to beginning. <strong><br><em>The final output of each time step is a concatenation of both the forward and backward RNNs which contains context from both directions.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*x7uyOQk-2ibvB8IaCcCKCg.jpeg" /><figcaption>Bidirectional-RNN taken from SPEECH RECOGNITION WITH DEEP RECURRENT NEURAL NETWORKS by Alex Graves, Abdel-rahman Mohamed and Geoffrey Hinton Department of Computer Science, University of Toronto</figcaption></figure><p>Architecture and Mathematical Formulations :<br>To formally understand the architecture, let us break it down :</p><ol><li>Forward RNN: This layer processes the input sequence from the beginning to the end (left to right). <br>It follows the standard equation :</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*qyNKCHfqnnOfS25HPgy1Wg.png" /></figure><p>2. Backward RNN: This layer processes the input sequence from the end to the beginning (right to left). <br>It follows the standard equation :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*TSsKnmsLuQIxLBm5JrX9rQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*bIhGYPf3Z5BLoTcT1oFOoA.png" /></figure><p>3. Concatenation strategies : The most common strategy is to concatenate the outputs from both the forward and backward RNNs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/91/1*mkmeZv3iJ4Pz-igr2eJt6A.png" /></figure><p>4. Output : The output of the concatenation is finally computed as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*bGRIU0RVrfwFdwfomyV3mQ.png" /></figure><p>Architectural diagram :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*P8UWG6Dzs2ujpx2sMmcULQ.png" /></figure><p><strong>Why choose Bi-RNNs for speech recognition ?</strong></p><p>Understanding phonemes, words, and phrases in speech recognition relies on both previous and following sounds. For instance, a word’s pronunciation may change depending on the words that surround it. Bi-RNNs take use of this by taking into account both historical and upcoming audio characteristics, which leads to:</p><p>1. <strong>Increased phoneme categorization accuracy</strong> : Bi-RNNs excel at <em>pronunciation handling</em> reducing errors due to accent mismatch and speech variations.</p><p>2.<strong> Improved management of co-articulation effects</strong>: The architecture captures fluidity in speech making them effective for connected or slurred speech and handling them accurately.</p><p>3.<strong> Learning long-range dependencies</strong> : The architecture also improved <em>speech-to-text</em> accuracy by learning long range past and future linguistic context.</p><p><strong>Architecture of Bi-RNN for speech recognition :</strong> <br>A Bi-RNN for speech recognition consist of multiple key components each playing a very important role in processing and transcribing of audio data. The Architecture typically includes :</p><ol><li><strong>Input Layer</strong> : The input layer extracts features such as speech signals like spectrogram or Mel-Spectrogram <br>These features serves as the numerical representation of the audio data capturing the frequency of the time-based audio data.</li><li><strong>Bi-directional RNN layer : </strong><br> We can use LSTM or GRU to handle long-range dependencies. Two RNNs are used to capture the context from both the forward and backward directions. <br>The outputs of both directions are concatenated to provide richer contextual understanding.</li><li><strong>Fully Connected Layer :</strong> It maps the concatenated output to the phenome or probability of words.<br>This layer helps in learning the complex relationships between the phenoms, words and patterns of the speech input.</li><li><strong>Soft max Layer :</strong> This layer is responsible for mapping the probability distribution of the possible output. <br>This layer ensures that the model only predicts the best possible output given the input speech segment.</li><li><strong>CTC Loss (Connectionist Temporal Classification) : </strong>Helps align variable-length speech inputs with text outputs giving us a end-to-end speech recognition. <br>The main importance of this loss is that it can recognize speech without perfectly aligned input-output pairs.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*eUuVmL0DvbhG71Z54PUTuw.gif" /></figure><p><strong>Code snippet for speech recognition :</strong></p><pre>import tensorflow as tf<br><br>from tensorflow.keras.layers import Input, Bidirectional, LSTM, Dense, Dropout<br>from tensorflow.keras.models import Model<br><br>def build_bi_rnn_speech_recognition(input_shape, num_classes):<br>    &quot;&quot;&quot;<br>    Builds a Bi-directional LSTM-based Speech Recognition Model.<br><br>    Parameters:<br>    - input_shape (tuple): Shape of input features (time_steps, feature_dim).<br>    - num_classes (int): Number of output classes (e.g., phoneme classes).<br><br>    Returns:<br>    - model (tf.keras.Model): Compiled Bi-directional LSTM model.<br>    &quot;&quot;&quot;<br><br>    # Define input layer<br>    inputs = Input(shape=input_shape, name=&quot;input_layer&quot;)<br><br>    # Bi-directional LSTM layer with dropout for regularization<br>    bi_lstm = Bidirectional(LSTM(128, return_sequences=True, dropout=0.2, recurrent_dropout=0.2),<br>                            name=&quot;bi_lstm_layer&quot;)(inputs)<br><br>    # Fully connected dense layer with ReLU activation<br>    dense = Dense(64, activation=&#39;relu&#39;, name=&quot;dense_layer&quot;)(bi_lstm)<br><br>    # Dropout layer for preventing overfitting<br>    dropout = Dropout(0.3, name=&quot;dropout_layer&quot;)(dense)<br><br>    # Output layer with softmax activation for classification<br>    outputs = Dense(num_classes, activation=&#39;softmax&#39;, name=&quot;output_layer&quot;)(dropout)<br><br>    # Create model<br>    model = Model(inputs, outputs, name=&quot;BiRNN_Speech_Recognition&quot;)<br>    <br>    # Compile model with categorical cross-entropy loss and Adam optimizer<br>    model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])<br><br>    return model<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    input_shape = (None, 40) <br>    num_classes = 30  <br><br>    model = build_bi_rnn_speech_recognition(input_shape, num_classes)<br>    model.summary()</pre><p><strong>Advantages of Bi-RNNs for speech recognition :</strong></p><ol><li><strong>Better Phoneme detection:</strong> By assessing both past and future frames, Bi-RNNs improve phoneme detection based on surrounding context.</li></ol><p>2. <strong>Improved Sentence-Level Understanding:</strong> Assists in the disambiguation of words and phrases with similar pronunciation but distinct meanings.</p><p>3. <strong>Handles Noisy Environments</strong>: It is resistant to background noise because it uses full context information.</p><p><strong>Conclusion </strong>:</p><p>Bi-directional RNNs have improved the evaluation of speech recognition by analyzing context from both front and back. Despite having some computational challenges, the architecture still remains one of the best approaches for Automatic Speech Recognition (ASR). Further research with hybrid models by incorporating transformers so that wecan further generalize the task so that it becomes more accurate and memory efficient.</p><p><strong>Citation : <br>1. </strong><a href="https://deeplearning.cs.cmu.edu/F20/document/readings/Bidirectional%20Recurrent%20Neural%20Networks.pdf"><strong>Schuster, M., &amp; Paliwal, K. K. (1997)</strong> </a>— The foundational paper on Bi-RNNs.</p><p><strong>2. </strong><a href="https://www.cs.toronto.edu/~fritz/absps/RNN13.pdf"><strong>Graves, A., Mohamed, A., &amp; Hinton, G. (2013)</strong></a> — A major paper on deep Bi-RNNs for speech recognition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ddb3dc43f66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyena Hierarchies : The future beyond transformers ?]]></title>
            <link>https://medium.com/@23subhasmukherjee/hyena-hierarchies-the-future-beyond-transformers-e1f31d42dd67?source=rss-34a20cdf5e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1f31d42dd67</guid>
            <dc:creator><![CDATA[Subhasmukherjee]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 19:49:23 GMT</pubDate>
            <atom:updated>2025-03-24T19:49:23.550Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hyena Hierarchies : The future beyond transformers ?</h3><p>Transformers have revolutionized Artificial Intelligence, powering everything from well-known GPT family to Stable Diffusion XL. But have you ever wondered if there is a much efficient and faster alternative lurking in the dark? Meet <em>Hyena Hierarchies — </em>a family of neural network architectures designed to replace traditional attention mechanism with long-range convolutions and structured hierarchies.<em> </em>In this blog we’ll talk about what Hyena hierarchies are, how they compare to transformers and how they might replace them.</p><p><strong>A Quick Recap of Transformers : <br></strong>Transformers are deep learning architecture that uses self-attention mechanisms and positional encodings to process entire sequences of data simultaneously. It allows each token to give importance to every other token. This becomes possible using the <strong>Query(Q)</strong>,<strong> Key(K)</strong> and <strong>Value(V)</strong> matrices combined in the formula :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*Zj_b6cpiJtyF4Tkr7AlgBQ.png" /></figure><p>This mechanism does capture the global dependencies but has a quadratic time and memory complexity. Transformers use positional encoding for sequential ordering of tokens. Although useful it becomes computationally expensive for transformers for very long sequences of data. This drawback led to further research and introduce Hyena Hierarchies which become efficient for long term dependencies by completely excluding attention using hierarchical structures.</p><p><strong>Hyena Hierarchies : What are they?<br></strong>Hyena Hierarchies were introduced in the year 2023 in the paper — “<a href="https://proceedings.mlr.press/v202/poli23a/poli23a.pdf">Hyena Hierarchy: Towards Larger Convolutional Language Models</a>”. It processes sequences by breaking them into chunks and analyzing relationships within and between chunks in a hierarchical manner. Instead of attending to each token independently in traditional transformer architecture it uses lightweight structured convolutions to mix local and global information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*FP_0r3Ae1X-_-EXYfK2Fhw.png" /><figcaption>A general architecture of Hyena Hierarchies</figcaption></figure><p><strong>Mathematical Formulation : </strong><br><strong>1. Token Mixing with Hierarchical Convolutions:</strong> <br> Split the sequence into chunks and apply multi-scale convolutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*VeW1IL2qkEs5xYW-VMqFNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*aZcXSWTt8tV2BolGizMTcA.png" /></figure><p><strong>2. Efficient parameterization with learnable kernels:</strong><br> Use parameterized convolutions for each scale, represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*MsYzsIZiuz2PkOcmITdlGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*05djWb5fjfp7l702EdfVuQ.png" /></figure><p><strong>3. Hierarchical Composition:</strong> <br> Combine local and global information using hierarchical aggregation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/1*0tseru6eD0DMPf6gLZF7eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*q74lJ6mxtQ67zVltCjeh8w.png" /></figure><h4>Step-by-step computational flow</h4><p><strong>Input Chunking:</strong> Split the input sequence into smaller, manageable chunks.</p><p><strong>Local Convolution:</strong> Apply lightweight convolution operations within each chunk to capture fine-grained patterns.</p><p><strong>Global Aggregation:</strong> Aggregate information hierarchically across chunks to capture long-range dependencies.</p><p><strong>Multi-Scale Fusion:</strong> Combine local and global patterns to generate the final output.</p><p><strong>Output Projection:</strong> Map the hierarchical features back to the original sequence dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*9N2UCb-6iaUBbKfHSljyRg.png" /><figcaption>Flowchart of Computational flow</figcaption></figure><p><strong>Hyena Hierarchies — Python Snippet :</strong></p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class HyenaBlock(nn.Module):<br>    &quot;&quot;&quot;<br>    A simplified implementation of Hyena Hierarchies block.<br>    <br>    Attributes:<br>        chunk_size (int): Size of each input chunk.<br>        conv_local (nn.Conv1d): Convolution for local (fine-grained) pattern extraction.<br>        conv_global (nn.Conv1d): Convolution for global (coarse) context aggregation.<br>        kernel_weights (nn.Parameter): Learnable weights for dynamic kernel computation.<br>        output_proj (nn.Linear): Linear layer for output projection.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, input_dim, chunk_size=16, kernel_size=3):<br>        super(HyenaBlock, self).__init__()<br>        self.chunk_size = chunk_size<br>        self.conv_local = nn.Conv1d(input_dim, input_dim, kernel_size, padding=1)<br>        self.conv_global = nn.Conv1d(input_dim, input_dim, kernel_size*2, padding=kernel_size)<br>        self.kernel_weights = nn.Parameter(torch.randn(kernel_size))<br>        self.output_proj = nn.Linear(input_dim, input_dim)<br>    <br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        Forward pass of Hyena Block.<br><br>        Args:<br>            x (Tensor): Input tensor of shape (batch_size, seq_len, input_dim)<br><br>        Returns:<br>            Tensor: Output tensor of shape (batch_size, seq_len, input_dim)<br>        &quot;&quot;&quot;<br>        batch_size, seq_len, dim = x.size()<br>        <br>        # Chunk the input sequence<br>        num_chunks = seq_len // self.chunk_size<br>        x_chunks = x.view(batch_size, num_chunks, self.chunk_size, dim)<br>        <br>        # Apply local and global convolutions on each chunk<br>        x_chunks = x_chunks.view(batch_size * num_chunks, self.chunk_size, dim).transpose(1, 2)  # (B*N, dim, chunk_size)<br>        local_feat = self.conv_local(x_chunks)<br>        global_feat = self.conv_global(x_chunks)<br>        <br>        # Merge local and global features<br>        fused_feat = local_feat + global_feat  # (B*N, dim, chunk_size)<br>        <br>        # Apply kernel weighting<br>        kernel = self.kernel_weights.view(1, -1, 1)  # (1, K, 1)<br>        weighted_feat = F.conv1d(fused_feat, kernel, padding=1)<br>        <br>        # Reshape back to original sequence shape<br>        weighted_feat = weighted_feat.transpose(1, 2).view(batch_size, seq_len, dim)<br>        <br>        # Final output projection<br>        out = self.output_proj(weighted_feat)<br>        <br>        return out<br></pre><pre>#How to use <br>model = HyenaBlock(input_dim=64, chunk_size=16)<br>dummy_input = torch.randn(8, 128, 64)  # (batch_size, seq_len, input_dim)<br>output = model(dummy_input)<br>print(output.shape)  </pre><p><strong>Why Hyena Hierarchies could outperform Transformers :</strong></p><p>1. Superior Long-Range Dependency: Hyena employs hierarchical convolutions that scale linearly with the length of the input, allowing it to effectively model long-range dependencies without the performance drawbacks associated with self-attention.</p><p>2. Memory and Computational Efficiency : The architecture introduces learned convolutional and parameterized kernels which makes it computationally cheaper and more memory efficient when we deploy it in low-end devices.</p><p>3. Aggregation to different scales: The architecture is designed to combine both local and global information using multi-scale fusion which not only capture fine grained information but also broader context via global aggregation.</p><p>4. Efficient use of parameters: It also uses much fewer parameters as because of the kernel learning and does not stack large attention heads or layers. This makes the model lightweight and parameter efficient.</p><p>Future Works:</p><p>While Hyena Hierarchies have shown positive results yet much more exploration and experimentation can be done in future. It has shown promising output with low computational overhead so future research can scale Hyena architecture for very large datasets and tasks like natural language understanding, vision-language models and reinforcement learning. Additionally experimenting with other models (hybrid models) can further improve generalization, real-time inference and scalability.</p><p><strong>Conclusion :</strong></p><p>The architecture represents a significant step forward in sequence modeling by offering many pros through learned convolutions, shared kernels and multi-scale aggregation. They successfully capture both local and global information with reduce memory usage. As the demand for powerful and efficient models grow in the field of AI, the demand for Hyena hierarchies may excel and play a crucial role in landscape of deep learning architectures.</p><h3>Citation (APA Style):</h3><p>Poli, M., Bubeck, S., Balestriero, R., Barham, N., &amp; LeCun, Y. (2023).<br> <strong>Hyena Hierarchies: Towards Larger Convolutional Language Models</strong>. <br> <a href="https://arxiv.org/abs/2302.10866">https://arxiv.org/abs/2302.10866</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1f31d42dd67" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>