<?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 Swastik on Medium]]></title>
        <description><![CDATA[Stories by Swastik on Medium]]></description>
        <link>https://medium.com/@kswastik29?source=rss-17649a99efa2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3DTC4sXCgIB5hNrEt8BOYg.jpeg</url>
            <title>Stories by Swastik on Medium</title>
            <link>https://medium.com/@kswastik29?source=rss-17649a99efa2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:41:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kswastik29/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[Understanding Dimension Importance Estimation (DIME) for Dense Information Retrieval through Code…]]></title>
            <link>https://medium.com/@kswastik29/understanding-dimension-importance-estimation-dime-for-dense-information-retrieval-through-code-ce2a1996ef48?source=rss-17649a99efa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce2a1996ef48</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <dc:creator><![CDATA[Swastik]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 02:31:43 GMT</pubDate>
            <atom:updated>2025-07-15T06:07:33.484Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Dimension Importance Estimation (DIME) for Dense Information Retrieval through Code and Experimentation</h3><h3>Introduction</h3><p>Dense embedding-based retrieval is being widely adapted in recent days. Unlike traditional sparse methods like BM25, which are based on lexical matching, dense embeddings capture semantic relationships and represent data in fixed-sized vectors ranging from a few hundreds to a few thousands. Each coordinate/dimension in the learned representation corresponds to some latent feature of the input data. For example, when text data is encoded into dense embeddings<strong>,</strong> it could represent various linguistic features, semantic meaning, conceptual features, etc. These are represented as floating numbers in vectors and are<strong> </strong>almost impossible for humans to interpret what the numbers actually encode.</p><p>This is one of the main reasons why dense embeddings tend to be more powerful than traditional methods, but in recent few years, people started noticing the noise these dense embeddings introduce along with the features. Let’s say when a query is represented with a dense embedding, only some part of the embedding could encode meaningful features, and the rest can be noise. When the same embedding is used to retrieve documents, the retrieval can be poor because of the noise. Hence, it is essential to keep only dimensions which encode meaningful features and exclude noise during retrieval.</p><p>But as I mentioned earlier, these embeddings are learned representations (mostly from deep learning models) which encode latent features; identifying the meaningful dimensions is not straightforward.</p><p>A paper released in 2024 called “Dimension Importance Estimation for Dense Information Retrieval” proposes various approaches to prune irrelevant dimensions. Recently, Pinecone did some deeper analysis on these approaches and released another paper with code. In this article, I’ll be going through some of the key details from these.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdd0vUBCo6Dn5wwuFRSqig.png" /></figure><h3>DIME Framework</h3><p>A simple goal here is to identify all irrelevant features (noise) from the dense embedding and zero them out to create another dense embedding which contains only the relevant features.</p><p>In a typical workflow, documents are embedded and stored. A query is embedded and queried on documents to retrieve relevant documents.</p><p>When the query is converted to an embedding, the DIME framework takes the query embedding, applies one of the below approaches, and transforms the query embedding by zeroing out all irrelevant dimensions.</p><p>In short, DIME acts on query embedding on the fly, thus requiring no retraining or reindexing. Once the query embedding is transformed, it can be either used for reranking or refetching.</p><pre>Q = [q1, q2, q3, q4, q5, q6] -&gt; [q1, 0, q3, q4, 0, 0]</pre><p><strong>Appraoches</strong></p><ol><li>Magnitude DIME</li><li>PRF DIME</li><li>LLM DIME</li><li>Active Feedback DIME</li></ol><h4><strong>Magnitude DIME</strong></h4><p>It is one of the simplest methods; here, the magnitude of the dimension is used to determine the importance of the dimension. The assumption is: the larger the magnitude, the more important the dimension is; lesser magnitude dimensions are noise or less relevant.</p><pre>q(i) = ∣qi∣ for all i∈[1,N] where N is the total number of dimensions in Q.</pre><p>This method relies solely on the query embedding itself to determine the importance of the dimension; the rest of all methods require another reference embedding which helps in deciding the importance of the dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*zkhAVWxF1RlUk2ZYsHaF9A.jpeg" /></figure><pre>class MagnitudeBasedDIME:<br>    ...<br><br>    def magnitude_rerank(self, query, initial_top_k=1000, final_top_k=10, zero_out_ratio=0.2):<br>        # Compute dimension importance using magnitude<br>        print(f&quot;Computing dimension importance using magnitude...&quot;)<br>        importance_scores = np.abs(original_query_embedding)<br>        <br>        # Zero out least important dimensions based on magnitude<br>        print(f&quot;Zeroing out {zero_out_ratio*100}% least important dimensions...&quot;)<br>        alpha = 1 - zero_out_ratio<br>        modified_query_embedding = self._zero_out_by_magnitude(original_query_embedding, importance_scores, alpha)<br>        <br>        # Re-score all initial results with modified query<br>        print(f&quot;Re-scoring with modified query...&quot;)<br>        reranked_results = []<br>        for result in initial_results:<br>            new_score = float(np.dot(modified_query_embedding, result[&#39;embedding&#39;]))<br>            reranked_results.append({<br>                &#39;rank&#39;: result[&#39;rank&#39;],<br>                &#39;index&#39;: result[&#39;index&#39;],<br>                &#39;product_id&#39;: result[&#39;product_id&#39;],<br>                &#39;title&#39;: result[&#39;title&#39;],<br>                &#39;original_score&#39;: result[&#39;score&#39;],<br>                &#39;new_score&#39;: new_score<br>            })<br>         <br>        # Sort by new scores and take top-k<br>        reranked_results.sort(key=lambda x: -x[&#39;new_score&#39;])<br>        final_results = reranked_results[:final_top_k]<br>        ...<br>    <br>    def magnitude_refetch(self, query, final_top_k=10, zero_out_ratio=0.2):<br>        # Compute dimension importance using magnitude<br>        print(f&quot;Computing dimension importance using magnitude...&quot;)<br>        importance_scores = np.abs(original_query_embedding)<br>        <br>        # Zero out least important dimensions based on magnitude<br>        print(f&quot;Zeroing out {zero_out_ratio*100}% least important dimensions...&quot;)<br>        alpha = 1 - zero_out_ratio<br>        modified_query_embedding = self._zero_out_by_magnitude(original_query_embedding, importance_scores, alpha)<br>        <br>        # Perform new retrieval with modified query<br>        print(f&quot;Performing new retrieval with modified query...&quot;)<br>        refetch_scores = np.dot(self.embeddings, modified_query_embedding)<br>        top_indices = np.argsort(refetch_scores)[::-1][:final_top_k]<br>        <br>        refetched_results = []<br>        for i, idx in enumerate(top_indices):<br>            refetched_results.append({<br>                &#39;rank&#39;: i + 1,<br>                &#39;index&#39;: idx,<br>                &#39;product_id&#39;: self.df.iloc[idx][&#39;product_id&#39;],<br>                &#39;title&#39;: self.df.iloc[idx][&#39;title&#39;],<br>                &#39;score&#39;: refetch_scores[idx]<br>            })<br>        ...<br>    <br>    def _zero_out_by_magnitude(self, query_vector, importance_scores, alpha=0.8):<br>        &quot;&quot;&quot;<br>        Zero out the lowest (1-alpha) fraction of dimensions based on magnitude importance<br>        <br>        Args:<br>            query_vector: Original query vector<br>            importance_scores: Magnitude-based importance scores (|qi|)<br>            alpha: Fraction of dimensions to keep (0.8 means keep 80%)<br>            <br>        Returns:<br>            Modified query vector with least important dimensions zeroed out<br>        &quot;&quot;&quot;<br>        dim = len(importance_scores)<br>        keep_count = int(alpha * dim)<br>        <br>        if keep_count &gt;= dim:<br>            return query_vector.copy()<br>        <br>        # Get indices of most important dimensions (highest magnitude)<br>        sorted_indices = np.argsort(importance_scores)<br>        keep_indices = set(sorted_indices[-keep_count:])<br>        <br>        # Zero out least important dimensions<br>        modified_query_vector = query_vector.copy()<br>        for i in range(dim):<br>            if i not in keep_indices:<br>                modified_query_vector[i] = 0.0<br>        <br>        return modified_query_vector<br><br># Initialize Magnitude-based DIME<br>magnitude_dime = MagnitudeBasedDIME(model, product_embeddings, df)<br>print(&quot;Magnitude-based DIME initialized successfully!&quot;)</pre><p>Here, zero_out_ratio is a hyperparameter which tells how many dimensions to prune. The same hyperparameter is used across all methods.</p><p><strong>Note:</strong> <em>It is important to keep in mind that none of the approaches exactly pinpoint whether a dimension is important or not; it is all relative, so it is us who decide what fraction of dimensions to prune, depending on how important we decide it is and how we decide that is using these 4 approaches.</em></p><p>Before we move to next approaches, I want to recall one of the points I mentioned earlier: to determine the importance of the dimension, all approaches except Magnitude DIME rely on a reference embedding. All 3 upcoming approaches differ in the way how they construct that reference embedding, and rest all concepts remain more or less same.</p><h4>Why Reference Embedding Needed?</h4><p>In order to determine the importance of a dimension, we need some sort of scoring mechanism which assigns scores to each dimension, and then we can prune a percentage of dimensions with less score. In the previous approach, we directly considered magnitude as the score, but in rest of the approaches, we rely on some reference embedding and then calculate the score of the dimension by performing element-wise multiplication — [qi​⋅ri​]. Hence, we need to make sure that the reference embedding can’t be just some random embedding; instead, it should be <strong>something relevant to the query embedding.</strong></p><h4>PRF (Pseudo-Relevance Feedback) DIME</h4><p>This approach is based on the assumption that the initial documents of the top-k retrieved documents are most likely to be relevant to the query. Here, we take prf_k (prf ≤ top-k), compute a centroid embedding from these embeddings, and consider this centroid embedding as the reference embedding, which is then used to calculate the dimension score by performing element-wise multiplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*YYB9R6M-BQfh5eyMnHbkEA.jpeg" /></figure><pre>def zero_out_least_important_dims(centroid, query_vector, alpha=0.8):<br>    &quot;&quot;&quot;<br>    Zero out the lowest (1-alpha) fraction of dimensions in query_vector<br>    based on element-wise product between centroid and query_vector<br>    <br>    Args:<br>        centroid: Centroid vector for dimension importance<br>        query_vector: Original query vector<br>        alpha: Fraction of dimensions to keep (0.8 means keep 80%)<br>        <br>    Returns:<br>        Modified query vector with least important dimensions zeroed out<br>    &quot;&quot;&quot;<br>    # Element-wise product to determine dimension importance<br>    importance_vec = np.multiply(centroid, query_vector)<br>    dim = len(importance_vec)<br>    keep_count = int(alpha * dim)<br>    <br>    if keep_count &gt;= dim:<br>        return query_vector.copy()<br>    <br>    # Get indices of most important dimensions<br>    sorted_indices = np.argsort(importance_vec)<br>    keep_indices = set(sorted_indices[-keep_count:])<br>    <br>    # Zero out least important dimensions<br>    modified_query_vector = query_vector.copy()<br>    for i in range(dim):<br>        if i not in keep_indices:<br>            modified_query_vector[i] = 0.0<br>    <br>    return modified_query_vector</pre><pre>class PRFBasedDIME:<br>    ...<br>        <br>    def prf_rerank(self, query, initial_top_k=1000, prf_k=10, final_top_k=10, <br>                   zero_out_ratio=0.2, weighted=False, attention_type=&quot;linear&quot;, temperature=1.0):<br><br><br>        # Compute centroid from top-k PRF documents<br>        print(f&quot;Computing centroid from top-{prf_k} PRF documents...&quot;)<br>        prf_embeddings = np.array([r[&#39;embedding&#39;] for r in initial_results[:prf_k]])<br>        prf_scores = np.array([r[&#39;score&#39;] for r in initial_results[:prf_k]])<br>        <br>        centroid = compute_centroid(prf_embeddings, prf_scores, k=None, <br>                                  weighted=weighted, attention_type=attention_type, <br>                                  temperature=temperature)<br>        <br>        # Zero out least important dimensions<br>        print(f&quot;Zeroing out {zero_out_ratio*100}% least important dimensions...&quot;)<br>        alpha = 1 - zero_out_ratio<br>        modified_query_embedding = zero_out_least_important_dims(centroid, original_query_embedding, alpha)<br>        <br>        # Re-score all initial results with modified query<br>        print(f&quot;Re-scoring with modified query...&quot;)<br>        reranked_results = []<br>        for result in initial_results:<br>            new_score = float(np.dot(modified_query_embedding, result[&#39;embedding&#39;]))<br>            reranked_results.append({<br>                &#39;rank&#39;: result[&#39;rank&#39;],<br>                &#39;index&#39;: result[&#39;index&#39;],<br>                &#39;product_id&#39;: result[&#39;product_id&#39;],<br>                &#39;title&#39;: result[&#39;title&#39;],<br>                &#39;original_score&#39;: result[&#39;score&#39;],<br>                &#39;new_score&#39;: new_score<br>            })<br>        <br>        # Sort by new scores and take top-k<br>        reranked_results.sort(key=lambda x: -x[&#39;new_score&#39;])<br>        final_results = reranked_results[:final_top_k]<br>        <br>        ...<br>    <br>    def prf_refetch(self, query, initial_top_k=1000, prf_k=10, final_top_k=10, <br>                    zero_out_ratio=0.2, weighted=False, attention_type=&quot;linear&quot;, temperature=1.0):<br><br>        # Compute centroid from top-k PRF documents<br>        print(f&quot;Computing centroid from top-{prf_k} PRF documents...&quot;)<br>        prf_embeddings = np.array([r[&#39;embedding&#39;] for r in initial_results[:prf_k]])<br>        prf_scores = np.array([r[&#39;score&#39;] for r in initial_results[:prf_k]])<br>        <br>        centroid = compute_centroid(prf_embeddings, prf_scores, k=None, <br>                                  weighted=weighted, attention_type=attention_type, <br>                                  temperature=temperature)<br>        <br>        # Zero out least important dimensions<br>        print(f&quot;Zeroing out {zero_out_ratio*100}% least important dimensions...&quot;)<br>        alpha = 1 - zero_out_ratio<br>        modified_query_embedding = zero_out_least_important_dims(centroid, original_query_embedding, alpha)<br>        <br>        # Perform new retrieval with modified query<br>        print(f&quot;Performing new retrieval with modified query...&quot;)<br>        refetch_scores = np.dot(self.embeddings, modified_query_embedding)<br>        top_indices = np.argsort(refetch_scores)[::-1][:final_top_k]<br>        <br>        refetched_results = []<br>        for i, idx in enumerate(top_indices):<br>            refetched_results.append({<br>                &#39;rank&#39;: i + 1,<br>                &#39;index&#39;: idx,<br>                &#39;product_id&#39;: self.df.iloc[idx][&#39;product_id&#39;],<br>                &#39;title&#39;: self.df.iloc[idx][&#39;title&#39;],<br>                &#39;score&#39;: refetch_scores[idx]<br>            })<br>        ... <br><br># Initialize PRF-based DIME<br>prf_dime = PRFBasedDIME(model, product_embeddings, df)<br>print(&quot;PRF-based DIME initialized successfully!&quot;)</pre><p>Here, Pinecone proposed an enhancement in calculating the centroid of the prf_k document embeddings. In the original paper, centroid calculation was just an arithmetic mean, but considering that in top-k documents not all documents are equally relevant to the query (the first document is highly relevant than the third one, for example), providing some weight for each document embedding can improve the reference embedding quality furthermore. To calculate this weight, Pinecone proposed simple linear weighting and softmax-based weighting methods.</p><p>More about the implementation of the weighting logic can be found <a href="https://github.com/pinecone-io/unveiling-dime/blob/main/tool/query.py#L213">here</a>.</p><h4>LLM DIME</h4><p>If you have worked on RAG, you would have probably heard of a technique called Hypothetical Document Embeddings (HyDE). In a typical scenario, a query is converted to an embedding and then used to retrieve a document. This could lead to asymmetric search where the query can be small and documents can be large. To tackle this, HyDE can be helpful. Here, an LLM is instructed to generate a Hypothetical Document for the query, which is then encoded and used for retrieval.</p><p>In this approach, the encoded Hypothetical Document can be used as a reference embedding to determine dimension importance. This completely makes sense because the main criteria for a reference embedding is that it should be relevant to the query embedding. In the PRF DIME approach, we used top relevant documents to calculate that, but here we use an LLM to create that document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*H1mzKRGeE3aQLCqDtXVW3A.jpeg" /></figure><pre>class LLMBasedDIME:<br>    ...<br>        <br>    def generate_llm_doc(self, query):<br>        &quot;&quot;&quot;<br>        Generate LLM-style document for the query<br>        Since we don&#39;t have actual LLM, we&#39;ll simulate by creating expanded query<br>        &quot;&quot;&quot;<br>        # Simple expansion - in real implementation, this would use an LLM<br>        expanded_queries = {<br>            &quot;black dress shirt&quot;: &quot;elegant black dress shirt formal business professional men&#39;s clothing cotton long sleeve button up office wear&quot;,<br>            &quot;blue jeans&quot;: &quot;blue denim jeans casual wear pants trousers men women comfortable cotton everyday fashion&quot;,<br>            &quot;white sneakers&quot;: &quot;white athletic sneakers shoes casual sports footwear comfortable rubber sole walking running&quot;,<br>            &quot;red dress&quot;: &quot;red dress women&#39;s formal elegant party evening wear special occasion outfit stylish&quot;,<br>            &quot;brown leather boots&quot;: &quot;brown leather boots shoes footwear men&#39;s outdoor durable sturdy walking hiking&quot;,<br>            &quot;casual t-shirt&quot;: &quot;casual t-shirt comfortable cotton everyday wear men women basic wardrobe essential&quot;,<br>            &quot;winter coat&quot;: &quot;winter coat warm jacket outerwear cold weather protection insulated heavy duty&quot;,<br>            &quot;summer dress&quot;: &quot;summer dress light breathable women&#39;s warm weather casual comfortable seasonal clothing&quot;<br>        }<br>    <br>        <br>        return expanded_queries[query]<br>    <br>    def llm_rerank(self, query, initial_top_k=1000, final_top_k=10, zero_out_ratio=0.2):<br><br>        # Generate LLM document and embed it<br>        print(f&quot;Generating and embedding LLM document...&quot;)<br>        llm_doc = self.generate_llm_doc(query)<br>        print(f&quot;Generated LLM doc: {llm_doc}&quot;)<br>        llm_embedding = self.model.encode([llm_doc], normalize_embeddings=True)[0]<br>        <br>        # Zero out least important dimensions using LLM embedding<br>        print(f&quot;Zeroing out {zero_out_ratio*100}% least important dimensions...&quot;)<br>        alpha = 1 - zero_out_ratio<br>        modified_query_embedding = zero_out_least_important_dims(llm_embedding, original_query_embedding, alpha)<br>        <br>        # Re-score all initial results with modified query<br>        print(f&quot;Re-scoring with modified query...&quot;)<br>        reranked_results = []<br>        for result in initial_results:<br>            new_score = float(np.dot(modified_query_embedding, result[&#39;embedding&#39;]))<br>            reranked_results.append({<br>                &#39;rank&#39;: result[&#39;rank&#39;],<br>                &#39;index&#39;: result[&#39;index&#39;],<br>                &#39;product_id&#39;: result[&#39;product_id&#39;],<br>                &#39;title&#39;: result[&#39;title&#39;],<br>                &#39;original_score&#39;: result[&#39;score&#39;],<br>                &#39;new_score&#39;: new_score<br>            })<br>        <br>        # Sort by new scores and take top-k<br>        reranked_results.sort(key=lambda x: -x[&#39;new_score&#39;])<br>        final_results = reranked_results[:final_top_k]<br>        ...<br>    <br>    def llm_refetch(self, query, final_top_k=10, zero_out_ratio=0.2):<br><br>        # Generate LLM document and embed it<br>        print(f&quot;Generating and embedding LLM document...&quot;)<br>        llm_doc = self.generate_llm_doc(query)<br>        print(f&quot;Generated LLM doc: {llm_doc}&quot;)<br>        llm_embedding = self.model.encode([llm_doc], normalize_embeddings=True)[0]<br>        <br>        # Zero out least important dimensions using LLM embedding<br>        print(f&quot;Zeroing out {zero_out_ratio*100}% least important dimensions...&quot;)<br>        alpha = 1 - zero_out_ratio<br>        modified_query_embedding = zero_out_least_important_dims(llm_embedding, original_query_embedding, alpha)<br>        <br>        # Perform new retrieval with modified query<br>        print(f&quot;Performing new retrieval with modified query...&quot;)<br>        refetch_scores = np.dot(self.embeddings, modified_query_embedding)<br>        top_indices = np.argsort(refetch_scores)[::-1][:final_top_k]<br>        <br>        refetched_results = []<br>        for i, idx in enumerate(top_indices):<br>            refetched_results.append({<br>                &#39;rank&#39;: i + 1,<br>                &#39;index&#39;: idx,<br>                &#39;product_id&#39;: self.df.iloc[idx][&#39;product_id&#39;],<br>                &#39;title&#39;: self.df.iloc[idx][&#39;title&#39;],<br>                &#39;score&#39;: refetch_scores[idx]<br>            })<br>        ...<br><br># Initialize LLM-based DIME<br>llm_dime = LLMBasedDIME(model, product_embeddings, df)<br>print(&quot;LLM-based DIME initialized successfully!&quot;)</pre><h4>Active-Feedback DIME</h4><p>This method is very much similar to LLM DIME, but here instead of using an LLM to generate a relevant document, a human-assessed document is considered as the reference document. This might be useful in scenarios where a user asks a question and the search engine returns results. If the user then clicks on one of them, the document user clicked can be considered as the relevant document, and then the results can be refined.</p><h3>Results Comparison</h3><p>We have covered all four approaches, and I’ve conducted small experiments on my end on some sample data to quickly check the results.</p><pre>test_queries = [<br>    &quot;black dress shirt&quot;,<br>    &quot;blue jeans&quot;,<br>    &quot;white sneakers&quot;,<br>    &quot;red dress&quot;,<br>    &quot;casual t-shirt&quot;,<br>    &quot;winter coat&quot;,<br>    &quot;summer dress&quot;,<br>]<br><br>================================================================================<br>RESULTS COMPARISON FOR: &#39;black dress shirt&#39;<br>================================================================================<br><br>BASELINE (Original Dense Retrieval):<br>--------------------------------------------------<br>1. J.Crew Black Blouses - Score: 0.5945<br>2. Gap Black Blouses - Score: 0.5807<br>3. Hollister Black T-Shirts in Viscose - Score: 0.5762<br>4. American Eagle Black T-Shirts - Score: 0.5690<br>5. Burberry Black Casual Shirts in Viscose - Score: 0.5592<br><br>MAGNITUDE RERANK:<br>--------------------------------------------------<br>1. J.Crew Black Blouses - Score: 0.5763<br>2. American Eagle Black T-Shirts - Score: 0.5584<br>3. Hollister Black T-Shirts in Viscose - Score: 0.5565<br>4. Gap Black Blouses - Score: 0.5536<br>5. Burberry Black Casual Shirts in Viscose - Score: 0.5353<br><br>MAGNITUDE REFETCH:<br>--------------------------------------------------<br>1. J.Crew Black Blouses - Score: 0.5763<br>2. American Eagle Black T-Shirts - Score: 0.5584<br>3. Hollister Black T-Shirts in Viscose - Score: 0.5565<br>4. Gap Black Blouses - Score: 0.5536<br>5. Burberry Black Casual Shirts in Viscose - Score: 0.5353<br><br>PRF RERANK:<br>--------------------------------------------------<br>1. Hollister Black T-Shirts in Viscose - Score: 0.6360<br>2. J.Crew Black Blouses - Score: 0.6217<br>3. American Eagle Black T-Shirts - Score: 0.6179<br>4. Burberry Black Casual Shirts in Viscose - Score: 0.6054<br>5. Gap Black Blouses - Score: 0.6006<br><br>PRF REFETCH:<br>--------------------------------------------------<br>1. Hollister Black T-Shirts in Viscose - Score: 0.6360<br>2. J.Crew Black Blouses - Score: 0.6217<br>3. American Eagle Black T-Shirts - Score: 0.6179<br>4. Burberry Black Casual Shirts in Viscose - Score: 0.6054<br>5. Gap Black Blouses - Score: 0.6006<br><br>LLM RERANK:<br>--------------------------------------------------<br>1. J.Crew Black Blouses - Score: 0.5135<br>2. Hollister Black Swimwear - Score: 0.5121<br>3. Burberry Black Casual Shirts in Viscose - Score: 0.5108<br>4. Hollister Black T-Shirts in Viscose - Score: 0.5010<br>5. American Eagle Black T-Shirts - Score: 0.4955<br>   LLM Doc: elegant black dress shirt formal business professional men&#39;s clothing cotton long sleeve button up o...<br><br>LLM REFETCH:<br>--------------------------------------------------<br>1. J.Crew Black Blouses - Score: 0.5135<br>2. Hollister Black Swimwear - Score: 0.5121<br>3. Burberry Black Casual Shirts in Viscose - Score: 0.5108<br>4. Hollister Black T-Shirts in Viscose - Score: 0.5010<br>5. American Eagle Black T-Shirts - Score: 0.4955<br>   LLM Doc: elegant black dress shirt formal business professional men&#39;s clothing cotton long sleeve button up o...<br><br>================================================================================<br>RESULTS COMPARISON FOR: &#39;blue jeans&#39;<br>================================================================================<br><br>BASELINE (Original Dense Retrieval):<br>--------------------------------------------------<br>1. Gap Blue Jeans in Suede - Score: 0.6695<br>2. Hollister Blue Jeans in Acrylic - Score: 0.6394<br>3. COS Blue Jeans in Wool - Score: 0.6391<br>4. J.Crew Blue Skirts in Denim - Score: 0.6225<br>5. COS Purple Jeans - Score: 0.6168<br><br>MAGNITUDE RERANK:<br>--------------------------------------------------<br>1. Gap Blue Jeans in Suede - Score: 0.6434<br>2. Hollister Blue Jeans in Acrylic - Score: 0.6290<br>3. COS Blue Jeans in Wool - Score: 0.6151<br>4. PrettyLittleThing Brown Jeans - Score: 0.6008<br>5. J.Crew Blue Skirts in Denim - Score: 0.6000<br><br>MAGNITUDE REFETCH:<br>--------------------------------------------------<br>1. Gap Blue Jeans in Suede - Score: 0.6434<br>2. Hollister Blue Jeans in Acrylic - Score: 0.6290<br>3. COS Blue Jeans in Wool - Score: 0.6151<br>4. PrettyLittleThing Brown Jeans - Score: 0.6008<br>5. J.Crew Blue Skirts in Denim - Score: 0.6000<br><br>PRF RERANK:<br>--------------------------------------------------<br>1. Gap Blue Jeans in Suede - Score: 0.6818<br>2. Hollister Blue Jeans in Acrylic - Score: 0.6659<br>3. COS Blue Jeans in Wool - Score: 0.6616<br>4. J.Crew Blue Skirts in Denim - Score: 0.6437<br>5. COS Purple Jeans - Score: 0.6362<br><br>PRF REFETCH:<br>--------------------------------------------------<br>1. Gap Blue Jeans in Suede - Score: 0.6818<br>2. Hollister Blue Jeans in Acrylic - Score: 0.6659<br>3. COS Blue Jeans in Wool - Score: 0.6616<br>4. J.Crew Blue Skirts in Denim - Score: 0.6437<br>5. COS Purple Jeans - Score: 0.6362<br><br>LLM RERANK:<br>--------------------------------------------------<br>1. Gap Blue Jeans in Suede - Score: 0.6223<br>2. Hollister Blue Jeans in Acrylic - Score: 0.6096<br>3. COS Blue Jeans in Wool - Score: 0.5948<br>4. COS Purple Jeans - Score: 0.5812<br>5. J.Crew Blue Skirts in Denim - Score: 0.5741<br>   LLM Doc: blue denim jeans casual wear pants trousers men women comfortable cotton everyday fashion...<br><br>LLM REFETCH:<br>--------------------------------------------------<br>1. Gap Blue Jeans in Suede - Score: 0.6223<br>2. Hollister Blue Jeans in Acrylic - Score: 0.6096<br>3. COS Blue Jeans in Wool - Score: 0.5948<br>4. COS Purple Jeans - Score: 0.5812<br>5. J.Crew Blue Skirts in Denim - Score: 0.5741<br>   LLM Doc: blue denim jeans casual wear pants trousers men women comfortable cotton everyday fashion...<br><br>================================================================================<br>RESULTS COMPARISON FOR: &#39;white sneakers&#39;<br>================================================================================<br><br>BASELINE (Original Dense Retrieval):<br>--------------------------------------------------<br>1. Gap White Sneakers - Score: 0.7189<br>2. Uniqlo White Sneakers in Leather - Score: 0.7051<br>3. COS Gray Sneakers - Score: 0.6921<br>4. Uniqlo White Sneakers in Polyester - Score: 0.6899<br>5. COS Gray Sneakers - Score: 0.6701<br><br>MAGNITUDE RERANK:<br>--------------------------------------------------<br>1. Gap White Sneakers - Score: 0.7004<br>2. Uniqlo White Sneakers in Leather - Score: 0.6812<br>3. COS Gray Sneakers - Score: 0.6802<br>4. Uniqlo White Sneakers in Polyester - Score: 0.6649<br>5. COS Gray Sneakers - Score: 0.6586<br><br>MAGNITUDE REFETCH:<br>--------------------------------------------------<br>1. Gap White Sneakers - Score: 0.7004<br>2. Uniqlo White Sneakers in Leather - Score: 0.6812<br>3. COS Gray Sneakers - Score: 0.6802<br>4. Uniqlo White Sneakers in Polyester - Score: 0.6649<br>5. COS Gray Sneakers - Score: 0.6586<br><br>PRF RERANK:<br>--------------------------------------------------<br>1. COS Gray Sneakers - Score: 0.7142<br>2. Gap White Sneakers - Score: 0.7111<br>3. Uniqlo White Sneakers in Leather - Score: 0.7105<br>4. Uniqlo White Sneakers in Polyester - Score: 0.6964<br>5. COS Gray Sneakers - Score: 0.6960<br><br>PRF REFETCH:<br>--------------------------------------------------<br>1. COS Gray Sneakers - Score: 0.7142<br>2. Gap White Sneakers - Score: 0.7111<br>3. Uniqlo White Sneakers in Leather - Score: 0.7105<br>4. Uniqlo White Sneakers in Polyester - Score: 0.6964<br>5. COS Gray Sneakers - Score: 0.6960<br><br>LLM RERANK:<br>--------------------------------------------------<br>1. Gap White Sneakers - Score: 0.6636<br>2. Uniqlo White Sneakers in Leather - Score: 0.6524<br>3. Uniqlo White Sneakers in Polyester - Score: 0.6317<br>4. COS Gray Sneakers - Score: 0.6177<br>5. COS Gray Sneakers - Score: 0.5995<br>   LLM Doc: white athletic sneakers shoes casual sports footwear comfortable rubber sole walking running...<br><br>LLM REFETCH:<br>--------------------------------------------------<br>1. Gap White Sneakers - Score: 0.6636<br>2. Uniqlo White Sneakers in Leather - Score: 0.6524<br>3. Uniqlo White Sneakers in Polyester - Score: 0.6317<br>4. COS Gray Sneakers - Score: 0.6177<br>5. COS Gray Sneakers - Score: 0.5995<br>   LLM Doc: white athletic sneakers shoes casual sports footwear comfortable rubber sole walking running...<br><br>================================================================================<br>RESULTS COMPARISON FOR: &#39;red dress&#39;<br>================================================================================<br><br>BASELINE (Original Dense Retrieval):<br>--------------------------------------------------<br>1. Hollister Red Formal Dresses in Denim - Score: 0.6673<br>2. H&amp;M Red Mini Dresses - Score: 0.6530<br>3. PrettyLittleThing Red Dress Pants - Score: 0.6506<br>4. H&amp;M Red Mini Dresses - Score: 0.6383<br>5. Hollister Red Dress Pants - Score: 0.6251<br><br>MAGNITUDE RERANK:<br>--------------------------------------------------<br>1. Hollister Red Formal Dresses in Denim - Score: 0.6338<br>2. PrettyLittleThing Red Dress Pants - Score: 0.6227<br>3. H&amp;M Red Mini Dresses - Score: 0.6088<br>4. Hollister Red Dress Pants - Score: 0.5950<br>5. H&amp;M Red Mini Dresses - Score: 0.5933<br><br>MAGNITUDE REFETCH:<br>--------------------------------------------------<br>1. Hollister Red Formal Dresses in Denim - Score: 0.6338<br>2. PrettyLittleThing Red Dress Pants - Score: 0.6227<br>3. H&amp;M Red Mini Dresses - Score: 0.6088<br>4. Hollister Red Dress Pants - Score: 0.5950<br>5. H&amp;M Red Mini Dresses - Score: 0.5933<br><br>PRF RERANK:<br>--------------------------------------------------<br>1. Hollister Red Formal Dresses in Denim - Score: 0.6886<br>2. PrettyLittleThing Red Dress Pants - Score: 0.6774<br>3. H&amp;M Red Mini Dresses - Score: 0.6726<br>4. H&amp;M Red Mini Dresses - Score: 0.6617<br>5. Hollister Red Dress Pants - Score: 0.6545<br><br>PRF REFETCH:<br>--------------------------------------------------<br>1. Hollister Red Formal Dresses in Denim - Score: 0.6886<br>2. PrettyLittleThing Red Dress Pants - Score: 0.6774<br>3. H&amp;M Red Mini Dresses - Score: 0.6726<br>4. H&amp;M Red Mini Dresses - Score: 0.6617<br>5. Hollister Red Dress Pants - Score: 0.6545<br><br>LLM RERANK:<br>--------------------------------------------------<br>1. Hollister Red Formal Dresses in Denim - Score: 0.6157<br>2. PrettyLittleThing Red Dress Pants - Score: 0.5996<br>3. H&amp;M Red Mini Dresses - Score: 0.5866<br>4. H&amp;M Red Mini Dresses - Score: 0.5728<br>5. Hollister Red Dress Pants - Score: 0.5676<br>   LLM Doc: red dress women&#39;s formal elegant party evening wear special occasion outfit stylish...<br><br>LLM REFETCH:<br>--------------------------------------------------<br>1. Hollister Red Formal Dresses in Denim - Score: 0.6157<br>2. PrettyLittleThing Red Dress Pants - Score: 0.5996<br>3. H&amp;M Red Mini Dresses - Score: 0.5866<br>4. H&amp;M Red Mini Dresses - Score: 0.5728<br>5. Hollister Red Dress Pants - Score: 0.5676<br>   LLM Doc: red dress women&#39;s formal elegant party evening wear special occasion outfit stylish...<br><br>================================================================================<br>RESULTS COMPARISON FOR: &#39;casual t-shirt&#39;<br>================================================================================<br><br>BASELINE (Original Dense Retrieval):<br>--------------------------------------------------<br>1. Old Navy Cream Casual Shirts - Score: 0.6248<br>2. Old Navy Cream T-Shirts - Score: 0.6002<br>3. Old Navy Gray Casual Shirts in Acrylic - Score: 0.5969<br>4. COS Brown Casual Shirts in Viscose - Score: 0.5862<br>5. Gucci Coral Casual Shirts - Score: 0.5825<br><br>MAGNITUDE RERANK:<br>--------------------------------------------------<br>1. Old Navy Cream Casual Shirts - Score: 0.5927<br>2. Old Navy Gray Casual Shirts in Acrylic - Score: 0.5698<br>3. Old Navy Cream T-Shirts - Score: 0.5624<br>4. Gucci Coral Casual Shirts - Score: 0.5551<br>5. American Eagle Black T-Shirts - Score: 0.5519<br><br>MAGNITUDE REFETCH:<br>--------------------------------------------------<br>1. Old Navy Cream Casual Shirts - Score: 0.5927<br>2. Old Navy Gray Casual Shirts in Acrylic - Score: 0.5698<br>3. Old Navy Cream T-Shirts - Score: 0.5624<br>4. Gucci Coral Casual Shirts - Score: 0.5551<br>5. American Eagle Black T-Shirts - Score: 0.5519<br><br>PRF RERANK:<br>--------------------------------------------------<br>1. Old Navy Cream Casual Shirts - Score: 0.6547<br>2. Old Navy Gray Casual Shirts in Acrylic - Score: 0.6384<br>3. Old Navy Cream T-Shirts - Score: 0.6215<br>4. Gucci Coral Casual Shirts - Score: 0.5988<br>5. Louis Vuitton Brown Casual Shirts in Acrylic - Score: 0.5975<br><br>PRF REFETCH:<br>--------------------------------------------------<br>1. Old Navy Cream Casual Shirts - Score: 0.6547<br>2. Old Navy Gray Casual Shirts in Acrylic - Score: 0.6384<br>3. Old Navy Cream T-Shirts - Score: 0.6215<br>4. Gucci Coral Casual Shirts - Score: 0.5988<br>5. Louis Vuitton Brown Casual Shirts in Acrylic - Score: 0.5975<br><br>LLM RERANK:<br>--------------------------------------------------<br>1. Old Navy Cream Casual Shirts - Score: 0.5722<br>2. Old Navy Cream T-Shirts - Score: 0.5485<br>3. Old Navy Gray Casual Shirts in Acrylic - Score: 0.5462<br>4. H&amp;M Coral Casual Shirts in Nylon - Score: 0.5434<br>5. Louis Vuitton Brown Casual Shirts in Acrylic - Score: 0.5424<br>   LLM Doc: casual t-shirt comfortable cotton everyday wear men women basic wardrobe essential...<br><br>LLM REFETCH:<br>--------------------------------------------------<br>1. Old Navy Cream Casual Shirts - Score: 0.5722<br>2. Old Navy Cream T-Shirts - Score: 0.5485<br>3. Old Navy Gray Casual Shirts in Acrylic - Score: 0.5462<br>4. H&amp;M Coral Casual Shirts in Nylon - Score: 0.5434<br>5. Louis Vuitton Brown Casual Shirts in Acrylic - Score: 0.5424<br>   LLM Doc: casual t-shirt comfortable cotton everyday wear men women basic wardrobe essential...<br><br>================================================================================<br>RESULTS COMPARISON FOR: &#39;winter coat&#39;<br>================================================================================<br><br>BASELINE (Original Dense Retrieval):<br>--------------------------------------------------<br>1. COS Black Coats - Score: 0.4631<br>2. COS Yellow Jackets - Score: 0.3912<br>3. Hollister Pink Jackets - Score: 0.3869<br>4. Primark Red Coats - Score: 0.3848<br>5. Old Navy Gray Coats - Score: 0.3797<br><br>MAGNITUDE RERANK:<br>--------------------------------------------------<br>1. COS Black Coats - Score: 0.4418<br>2. COS Yellow Jackets - Score: 0.3864<br>3. Hollister Pink Jackets - Score: 0.3705<br>4. Primark Red Coats - Score: 0.3651<br>5. Banana Republic Beige Jackets - Score: 0.3646<br><br>MAGNITUDE REFETCH:<br>--------------------------------------------------<br>1. COS Black Coats - Score: 0.4418<br>2. COS Yellow Jackets - Score: 0.3864<br>3. Hollister Pink Jackets - Score: 0.3705<br>4. Primark Red Coats - Score: 0.3651<br>5. Banana Republic Beige Jackets - Score: 0.3646<br><br>PRF RERANK:<br>--------------------------------------------------<br>1. COS Black Coats - Score: 0.5348<br>2. COS Yellow Jackets - Score: 0.4790<br>3. Hollister Pink Jackets - Score: 0.4511<br>4. Primark Red Coats - Score: 0.4453<br>5. COS Brown Jackets - Score: 0.4413<br><br>PRF REFETCH:<br>--------------------------------------------------<br>1. COS Black Coats - Score: 0.5348<br>2. COS Yellow Jackets - Score: 0.4790<br>3. Hollister Pink Jackets - Score: 0.4511<br>4. Primark Red Coats - Score: 0.4453<br>5. COS Brown Jackets - Score: 0.4413<br><br>LLM RERANK:<br>--------------------------------------------------<br>1. COS Black Coats - Score: 0.4076<br>2. COS Yellow Jackets - Score: 0.3869<br>3. American Eagle Orange Jackets in Wool - Score: 0.3624<br>4. J.Crew Red Jackets - Score: 0.3595<br>5. Hollister Pink Jackets - Score: 0.3579<br>   LLM Doc: winter coat warm jacket outerwear cold weather protection insulated heavy duty...<br><br>LLM REFETCH:<br>--------------------------------------------------<br>1. COS Black Coats - Score: 0.4076<br>2. COS Yellow Jackets - Score: 0.3869<br>3. American Eagle Orange Jackets in Wool - Score: 0.3624<br>4. J.Crew Red Jackets - Score: 0.3595<br>5. Hollister Pink Jackets - Score: 0.3579<br>   LLM Doc: winter coat warm jacket outerwear cold weather protection insulated heavy duty...<br><br>================================================================================<br>RESULTS COMPARISON FOR: &#39;summer dress&#39;<br>================================================================================<br><br>BASELINE (Original Dense Retrieval):<br>--------------------------------------------------<br>1. H&amp;M Yellow Mini Dresses - Score: 0.5662<br>2. PrettyLittleThing Yellow Mini Dresses - Score: 0.5450<br>3. H&amp;M Blue Mini Dresses - Score: 0.5306<br>4. COS Orange Casual Dresses - Score: 0.5261<br>5. H&amp;M Purple Dresses - Score: 0.5169<br><br>MAGNITUDE RERANK:<br>--------------------------------------------------<br>1. H&amp;M Yellow Mini Dresses - Score: 0.5466<br>2. PrettyLittleThing Yellow Mini Dresses - Score: 0.5250<br>3. H&amp;M Blue Mini Dresses - Score: 0.5131<br>4. H&amp;M Purple Dresses - Score: 0.5038<br>5. H&amp;M Green Casual Dresses - Score: 0.4964<br><br>MAGNITUDE REFETCH:<br>--------------------------------------------------<br>1. H&amp;M Yellow Mini Dresses - Score: 0.5466<br>2. PrettyLittleThing Yellow Mini Dresses - Score: 0.5250<br>3. H&amp;M Blue Mini Dresses - Score: 0.5131<br>4. H&amp;M Purple Dresses - Score: 0.5038<br>5. H&amp;M Green Casual Dresses - Score: 0.4964<br><br>PRF RERANK:<br>--------------------------------------------------<br>1. H&amp;M Yellow Mini Dresses - Score: 0.6422<br>2. PrettyLittleThing Yellow Mini Dresses - Score: 0.5932<br>3. H&amp;M Blue Mini Dresses - Score: 0.5884<br>4. H&amp;M Red Mini Dresses - Score: 0.5809<br>5. H&amp;M Purple Dresses - Score: 0.5752<br><br>PRF REFETCH:<br>--------------------------------------------------<br>1. H&amp;M Yellow Mini Dresses - Score: 0.6422<br>2. PrettyLittleThing Yellow Mini Dresses - Score: 0.5932<br>3. H&amp;M Blue Mini Dresses - Score: 0.5884<br>4. H&amp;M Red Mini Dresses - Score: 0.5809<br>5. H&amp;M Purple Dresses - Score: 0.5752<br><br>LLM RERANK:<br>--------------------------------------------------<br>1. H&amp;M Yellow Mini Dresses - Score: 0.5200<br>2. PrettyLittleThing Yellow Mini Dresses - Score: 0.4990<br>3. H&amp;M Green Casual Dresses - Score: 0.4982<br>4. H&amp;M Blue Mini Dresses - Score: 0.4922<br>5. COS Orange Casual Dresses - Score: 0.4880<br>   LLM Doc: summer dress light breathable women&#39;s warm weather casual comfortable seasonal clothing...<br><br>LLM REFETCH:<br>--------------------------------------------------<br>1. H&amp;M Yellow Mini Dresses - Score: 0.5200<br>2. PrettyLittleThing Yellow Mini Dresses - Score: 0.4990<br>3. H&amp;M Green Casual Dresses - Score: 0.4982<br>4. H&amp;M Blue Mini Dresses - Score: 0.4922<br>5. COS Orange Casual Dresses - Score: 0.4880<br>   LLM Doc: summer dress light breathable women&#39;s warm weather casual comfortable seasonal clothing...</pre><p>Overall, I found DIME helpful based on my minimal testing. One of the main reasons why this idea is impressive for me is because it requires no reindexing or retraining and is very easy to implement. If you ask me why choose this one when hundreds of different retrieval methods already exist, I would say it’s because of its simplicity. That being said, it requires some hyperparameter tuning and some figuring out the right DIME approach for your use case.</p><h3>Conclusion</h3><p>As said earlier, the main advantage of DIME is its simplicity and the fact that it gives better results without having to reindex or retrain. IMHO, I would suggest <strong>trying out the second and third methods (PRF &amp; LLM DIME)</strong> since the other two methods are not theoretically convincing for me.</p><p>I’m attaching the <a href="https://github.com/29swastik/DIME">github link</a> where you can find the sample dataset and notebook which I’ve used for quick testing.</p><h3>References</h3><p><a href="https://github.com/29swastik/DIME">https://github.com/29swastik/DIME</a></p><p><a href="https://github.com/pinecone-io/unveiling-dime">https://github.com/pinecone-io/unveiling-dime</a></p><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//www.pinecone.io/research/SIGIR25a.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8e9d6d3bfbd97314ba84af8d72779aa/href">https://medium.com/media/f8e9d6d3bfbd97314ba84af8d72779aa/href</a></iframe><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//www.dei.unipd.it/%7Eferro/papers/2024/SIGIR2024-FFPT.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/cadc92e7a6345016e10ab44d3a2763d2/href">https://medium.com/media/cadc92e7a6345016e10ab44d3a2763d2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce2a1996ef48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting the Dots: Cache-Augmented Generation (CAG) and Prompt Caching]]></title>
            <link>https://medium.com/@kswastik29/what-people-are-not-telling-you-is-that-cag-is-the-same-as-prompt-caching-e2b2fd3af1ea?source=rss-17649a99efa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2b2fd3af1ea</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Swastik]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 22:36:35 GMT</pubDate>
            <atom:updated>2025-01-27T02:59:45.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>What People Are Not Telling You Is That Cache-Augmented Generation (CAG) Is the Same as Prompt Caching</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFYUKHY-GySoHLVb5ydaYg.png" /></figure><h3>Introduction</h3><p>It’s been 2 years that LLM/RAG has come mainstream and we are also started to see how it evolving as a typical software engineering workflow which would have a caching layer, design patterns and principles etc. Building solutions around LLMs are no different in various aspects. Lots of methods / researches happening around this is now mostly kind of how we can optimise the solutions we build on top of LLM. One such is Don’t Do RAG: When Cache-Augmented Generation is All You Need for Knowledge Tasks which we will be talking about today.</p><h3>Quick Recap of Concepts</h3><h4><strong>Attention Mechanism During Inference in Decoder-Only Models (Autoregressive Models):</strong></h4><p>Decoder-only models process input tokens autoregressively, attending to all previously generated tokens during each step of inference. This ensures contextual understanding but can be computationally expensive for long sequences.</p><p>Attention mechanism mathematically represented like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*e_a5OBQhux59wUXJy3szyQ.png" /><figcaption>Attention Mechanism</figcaption></figure><p>Let’s walk through an example to tecall the Attention Mechanism and KV Cache.</p><p><strong>Example Sentence</strong></p><p>Consider a sentence: <strong>“The cat sat on the mat.”</strong></p><p>Each word is represented as an embedding vector of dimension dₖ = 4. Here’s the embedding matrix for simplicity:</p><ul><li>“The” → [1,0,1,0]</li><li>“cat” → [0,1,0,1]</li><li>“sat” → [1,1,0,0]</li><li>“on” → [0,0,1,1]</li><li>“the” → [1,0,0,1]</li><li>“mat” → [0,1,1,0]</li></ul><h4>Step 1: Creating Query (Q), Key (K), and Value (V)</h4><p>The model transforms each word embedding into Query (Q), Key (K), and Value (V) vectors using learned weight matrices:</p><p>Q=Wq⋅ embedding,</p><p>K=Wₖ​⋅embedding,</p><p>V=Wᵥ​⋅embedding</p><p>For simplicity, let’s assume:</p><ul><li>Wq = Wₖ = Wᵥ = I (Identity matrix).</li></ul><p>Thus, Q = K = V = embedding.</p><h4>Step 2: Compute Similarity Scores (QKᵀ)</h4><p>The dot product Q ⋅ Kᵀ measures the similarity of the Query for a token to all Keys. For the word “sat”:</p><p>Qₛₐₜ = [1,1,0,0]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*H08ifGcGvovo4baPQTU2Xw.png" /></figure><h4>Step 3: Scale and Normalize Scores</h4><p>The scores are scaled by √dₖ​​ (here √4 = 2) and passed through softmax to get attention weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*QD9uBHroa2T7NDe0mMo0Og.png" /></figure><h4>Step 4: Weighted Sum of Values</h4><p>The attention weights are multiplied by the Value matrix to compute the context vector for “sat.” The Value matrix is the same as the embedding matrix in our case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*9mSA2EKipZe-pYaGj1jbmg.png" /></figure><p>This results in a vector that represents the context of “sat” in the sentence, factoring in all words weighted by their relevance.</p><h4>KV Cache During Inference in Decoder-Only Models (Autoregressive Models):</h4><p>To reduce computational overhead, these models leverage Key-Value (KV) caching. This mechanism stores intermediate attention states, allowing the model to avoid recalculating attention weights for tokens it has already processed, thereby improving inference speed.</p><h4>Step 1: First Token (“The”)</h4><p>For the first token, no cache is available because no tokens have been processed yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*W6YuWLeqZ7unC-YrnU_iBw.png" /></figure><h4>Step 2: Second Token (“cat”)</h4><p>Now, the <strong>KV cache</strong> contains K1​ and V1​ from the first token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*RiETz9nNLDAbO-8o9it_uw.png" /></figure><h4>Step 3: Third Token (“sat”)</h4><p>The cache now contains K1, V1​ and K2V2​.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*dnMZhgsR98w2VGPXVedrjg.png" /></figure><p>The below GIF explains the concept in a much better way than text ever could. Pay special attention to the <strong>violet part</strong>, as it visually represents how the KV cache is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uyuyOW1VBqmF5Gtv225XHQ.gif" /><figcaption>Stolen from <a href="https://medium.com/u/baa7936a9fd">João Lages</a> - please have some mercy</figcaption></figure><h4>In Simple Terms</h4><p><strong>Without KV Cache:</strong> The model keeps repeating the same work for all previous words every time it processes a new one.<br><strong>With KV Cache: </strong>The model remembers what it already calculated and focuses only on the new word.</p><p>This makes the process <strong>faster and more efficient, especially for longer sentences.</strong></p><p><strong>Important:</strong> <em>The above KV caching happens for each token within a single inference request. Now, to move into the main discussion, imagine this same caching mechanism not being limited to a single inference request but extending across multiple requests.</em></p><h3>Prompt Caching</h3><p>Prompt Caching is an optimization technique designed to improve performance when a <strong>static content = same(prompt + context)</strong> is used repeatedly in multiple API calls to LLMs. By caching this static content, subsequent API calls avoid <strong><em>reprocessing</em></strong> the same content, reducing latency and costs.</p><h4>OpenAI</h4><blockquote>Prompt caching automatically activates for prompts longer than 1024 tokens — you don’t have to change anything in your completions request. When an API request is made, the system first checks if the beginning portion (prefix) of the prompt has already been cached. If a match is found (cache hit), the cached prompt is used, leading to reduced latency and costs. If there’s no match, the system processes the full prompt from scratch and caches the prefix for future use.</blockquote><blockquote>Model prompts often contain repetitive content, like system prompts and common instructions. OpenAI routes API requests to servers that recently processed the same prompt, making it cheaper and faster than <strong>processing</strong> a prompt from scratch. This can reduce latency by up to 80% and cost by 50% for long prompts. Prompt Caching works automatically on all your API requests (no code changes required) and has no additional fees associated with it.</blockquote><h4>Anthropic</h4><blockquote>Prompt caching is a powerful feature that optimizes your API usage by allowing resuming from specific prefixes in your prompts. This approach significantly reduces <strong>processing</strong> time and costs for repetitive tasks or prompts with consistent elements.</blockquote><p><strong>Note:</strong><em> Carefully observe that I’ve highlighted the </em><strong><em>processed </em></strong><em>word in the explanations above. This detail is very important and will play a significant role in our further discussion, so keep an eye on it.</em></p><h4>Example: Building a Q&amp;A Bot</h4><p>Let’s say you are building a Q&amp;A bot for a textbook. The <strong>Static Content</strong> in this case is the <strong>Prompt + Textbook Content</strong>, which remains the same for every query. Here’s how prompt caching helps:</p><ol><li><strong>First Query:</strong></li></ol><ul><li><strong>User Question:</strong> “What is photosynthesis?”</li><li>The static content (<strong>Prompt + Textbook</strong>) is sent along with the query to the LLM.</li><li>The system processes the static content, caches it, and answers the query.</li></ul><p><strong>2. Subsequent Queries:</strong></p><ul><li><strong>User Question:</strong> “What role do chloroplasts play in photosynthesis?”</li><li>Instead of processing the static content again, the LLM loads it from the cache and only processes the new query.</li><li>This results in <strong>faster inference</strong> and avoids redundant computation.</li></ul><p>If we agree up to this point and share the same understanding of the concept of prompt caching, then we are on the same page and good to proceed. However, if there’s anything unclear or you feel needs correction, please feel free to point it out!</p><p>Now let’s go to our main topic <strong>CAG</strong></p><h3><strong>CAG (Cache-Augmented Generation)</strong></h3><p>The <strong>Cache-Augmented Generation (CAG) framework</strong> leverages the ability of long-context LLMs to process large amounts of preloaded knowledge, enabling efficient, retrieval-free knowledge integration. This eliminates the challenges of traditional retrieval-augmented generation (RAG) systems, such as retrieval latency and errors. The framework operates in three key steps:</p><h4>1. External Knowledge Preloading</h4><ul><li>A collection of relevant documents D is preprocessed to fit within the model’s extended context window.</li><li>The LLM processes this data to create a <strong>Key-Value (KV) cache</strong>:</li></ul><pre>Cₖᵥ = KV-Encode(D)                               Cₖᵥ -&gt; KV cache</pre><ul><li>This cache stores the model’s inference state for the documents and is saved on <strong><em>disk or memory.</em></strong></li><li><strong>Cost incurred only once:</strong> Once the cache is created, it can be reused for any number of future queries.</li></ul><h4>2. Inference</h4><ul><li>When a user query Q is received, the <strong>precomputed KV cache</strong> Cₖᵥ is loaded along with the query.</li><li>The LLM uses the cached knowledge to generate a response: ```</li></ul><pre>R = LLM(Q∣Cₖᵥ)                                   R -&gt; Response</pre><ul><li>This step eliminates the need for real-time retrieval of documents, reducing latency and avoiding errors.</li></ul><h4>3. Cache Reset</h4><p>Skipping this in current discussion as it not relevant to our topic</p><p>With <strong>CAG</strong>, we preload all relevant documents into a long-context LLM. The model processes these documents to create a <strong>KV cache</strong>, which is saved in memory or on disk. During inference, the cache is loaded into the model, allowing efficient and retrieval-free query processing.</p><p><strong>Important: </strong><em>In the same post when we discussed about KV cache we were just referring to KV cache usage within a single inference request, but here it is extended across multiple requests.</em></p><h3>Why I Think CAG Talks About How Prompt Caching Is Implemented (Without Explicitly Saying So)</h3><p>In Prompt Caching we see one most highlighted word “<strong>processed</strong>” and in CAG we see one most word “<strong>KV cache</strong>”. While prompt caching is a concept introduced by big gaints OpenAI and Anthropic which are not opensource didn’t reveal much on what exact processing they are going to reduce in other words they technically didn’t reveal what/which processing is avoided by caching, but since we have an idea that these are deocoder only model and has attention mechanism at its heart we can say one of those processing they are talking about is KV cache. So in my opinion the CAG method essentially explains how prompt caching works i.e by creating KV cache which can be reused across multiple requests.</p><p>Before we conclude, there is one technique called <strong>Semantic Caching</strong>, which is totally different. It is a very first-level cache that caches the query and LLM response, and in subsequent requests, if the question is similar, it fetches the LLM response without even calling the LLM. But in the current discussion, caching happens at the LLM. Think of it as <strong>application-side caching</strong> (Semantic Cache) and <strong>server-side caching</strong> (Prompt Cache / CAG).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*1PHct37J0kI7dUi5Tc_gHQ.png" /></figure><h3>Conclusion</h3><p>There is no doubt that CAG is a great solution. I believe we can take it a step further by creating multiple KV caches across different sets of documents and using a lightweight classification model to select the right cache for a user query. This approach could completely avoid retrieval, even with larger document sets.</p><p>The primary reason for writing this article is that the paper didn’t mention anything about Prompt Caching, which led to some confusion. I might still be wrong in my understanding, but if CAG is indeed different from Prompt Caching, the paper could have clarified how it differs or explained why CAG is better.</p><h3><strong>References</strong></h3><ul><li><a href="https://arxiv.org/html/2412.15605v1">Don&#39;t Do RAG: When Cache-Augmented Generation is All You Need for Knowledge Tasks</a></li><li><a href="https://medium.com/@joaolages/kv-caching-explained-276520203249">KV Caching Explained</a></li><li><a href="https://www.anthropic.com/news/prompt-caching">Prompt caching with Claude | Claude by Anthropic</a></li></ul><p><a href="https://platform.openai.com/docs/guides/prompt-caching">https://platform.openai.com/docs/guides/prompt-caching</a></p><p><a href="https://www.youtube.com/watch?v=Mn_9W1nCFLo&amp;t=3050s">https://www.youtube.com/watch?v=Mn_9W1nCFLo&amp;t=3050s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2b2fd3af1ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Normalizing Cosine Similarity for Scoring: A Practical Approach]]></title>
            <link>https://medium.com/@kswastik29/normalizing-cosine-similarity-for-scoring-a-practical-approach-8df5e3d41876?source=rss-17649a99efa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8df5e3d41876</guid>
            <category><![CDATA[similarity-search]]></category>
            <category><![CDATA[cosine-similarity]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Swastik]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 03:28:40 GMT</pubDate>
            <atom:updated>2025-01-29T06:22:34.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9LHiv38Bz2ju1fSMdtECg.png" /></figure><h3>Introduction</h3><p>If you are working with vector databases and embeddings in any of your RAG, search, or recommendation systems, you would have seen these databases provide scores when queried with a vector. These scores are often used in downstream processes like ranking, filtering, and personalization. Understanding how these scores are derived and normalized can significantly improve how you interpret and leverage them in your applications.</p><h3>Background</h3><p>Under the hood, the database calculates the distance between the query vector and vectors stored in the database to find the nearest vectors. It then returns documents for those vectors along with a score, sorted by score. This score can be further used in application logic for various purposes, such as debugging, or for weighted calculations to influence the final ranking. For example, when fetching products from a vector database, you might assign a weightage of 0.7 to the score and 0.3 to total sales, affecting the final ordering of results. The final score can be calculated using a weighted sum formula:</p><pre>new_score = 0.7 * score + 0.3 * sales</pre><p>Note: In real-world scenarios, databases use indexes to speed up the process of finding nearest vectors using techniques like <a href="https://github.com/nmslib/hnswlib">HNSW</a> (Hierarchical Navigable Small World) or IVF (Inverted File Index). These are just optimizations and do not affect scoring. The indexes still rely on the same distance metrics to calculate scores.</p><p>When it comes to text similarity, a widely used distance metric is cosine similarity. Other metrics like Euclidean and Manhattan distances are also available, but for this discussion, we will focus on cosine similarity.</p><p>Most vector databases, such as Mongo Atlas and OpenSearch, provide flexibility to choose the distance metric. When cosine similarity is selected, these databases perform transformations to map cosine similarity values in the range [-1, 1] to scores in the range [0, 1].</p><h3>Converting Cosine Similarity to Score</h3><h3>Transformation Used by Mongo Atlas</h3><p><a href="https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-stage/#atlas-vector-search-score">Mongo Atlas</a> uses the following formula to transform cosine similarity:</p><pre>score = (1 + cosine(v1, v2)) / 2</pre><p><strong>Intuition:</strong> This formula shifts the cosine similarity range from [-1, 1] to [0, 2] by adding 1. Dividing by 2 then scales the range to [0, 1]. This approach effectively maps the similarity values into a normalized range suitable for ranking purposes, ensuring that higher similarity values translate directly to higher scores.</p><p>This formula normalizes cosine similarity from [-1, 1] to [0, 1]. Let’s see how this works for different values:</p><pre>cosine = -1<br>score = (1 + (-1)) / 2 = 0<br>------------------------------------<br>cosine = 0<br>score = (1 + 0) / 2 = 0.5<br>------------------------------------<br>cosine = 1<br>score = (1 + 1) / 2 = 1</pre><p><strong>Python Code Example:</strong></p><pre>import numpy as np<br>from numpy.linalg import norm<br><br>v1 = np.array([1, 0, 0])<br>v2 = np.array([0, 1, 0])<br><br>cos_sim = np.dot(v1, v2) / (norm(v1) * norm(v2))<br>score = (1 + cos_sim) / 2<br><br>print(&quot;Cosine Similarity:&quot;, cos_sim)<br>print(&quot;Normalized Score:&quot;, score)</pre><h3>Transformation Used by OpenSearch (NMSLIB and Faiss)</h3><p><a href="https://opensearch.org/docs/latest/search-plugins/knn/approximate-knn/#spaces">OpenSearch</a>, when using NMSLIB or Faiss, applies the following transformation:</p><pre>d = 1 - cos(theta)<br>score = 1 / (1 + d)</pre><p>Intuition: This formula treats the cosine similarity as a measure of closeness, where 1 — cos(theta) calculates the distance between vectors. The score is then derived by taking the inverse of (1 + distance). This ensures that smaller distances (higher similarities) yield higher scores, following an exponential decay-like behavior where distant points are scored much lower.</p><p>Let’s see examples:</p><pre>cosine = -1<br>d = 1 - (-1) = 2<br>score = 1 / (1 + 2) = 1 / 3 ≈ 0.33<br><br>cosine = 0<br>d = 1–0 = 1<br>score = 1 / (1 + 1) = 0.5<br><br>cosine = 1<br>d = 1–1 = 0<br>score = 1 / (1 + 0) = 1</pre><p><strong>Python Code Example:</strong></p><pre>import numpy as np<br>from numpy.linalg import norm<br><br>v1 = np.array([1, 0, 0])<br>v2 = np.array([0, 1, 0])<br><br>cos_sim = np.dot(v1, v2) / (norm(v1) * norm(v2))<br>d = 1 - cos_sim<br>score = 1 / (1 + d)<br><br>print(&quot;Cosine Similarity:&quot;, cos_sim)<br>print(&quot;Normalized Score:&quot;, score)</pre><h3>Conclusion</h3><p>Normalizing cosine similarity to scores in the range [0, 1] is crucial for simplifying downstream processes in applications like ranking and recommendations. It allows scores to be comparable across different queries and documents, making it easier to apply weighting logic or blending with other features like click-through rates or popularity metrics.</p><p>By understanding these transformations, developers can better interpret results from vector databases and optimize scoring strategies for their use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8df5e3d41876" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Python’s ThreadPoolExecutor Context Manager]]></title>
            <link>https://medium.com/@kswastik29/understanding-pythons-threadpoolexecutor-context-manager-508cc96f52b6?source=rss-17649a99efa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/508cc96f52b6</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[parallel-execution]]></category>
            <dc:creator><![CDATA[Swastik]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 14:26:22 GMT</pubDate>
            <atom:updated>2025-01-29T06:22:45.876Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mn836oLx1yiskIVhuYBlQg.jpeg" /></figure><p>A thread pool helps run tasks in parallel in Python, but sometimes your code might end up running tasks one after another instead of in parallel. Let’s see why this happens and how to fix it.</p><p>Imagine a product search service that needs to:</p><ol><li>Search product vectors</li><li>Perform full-text search</li><li>Fetch sponsored products</li></ol><h3>Initial Code</h3><pre>from concurrent.futures import ThreadPoolExecutor<br>import time<br><br>def vector_search(query):<br>    time.sleep(1)<br>    return [&quot;product1&quot;, &quot;product2&quot;]<br><br>def full_text_search(query):<br>    time.sleep(2)<br>    return [&quot;product3&quot;, &quot;product4&quot;]<br><br>def get_sponsored_products():<br>    time.sleep(3)<br>    return [&quot;sponsored1&quot;]<br><br>def search_products(query):<br>    with ThreadPoolExecutor(max_workers=2) as executor:<br>        vector_future = executor.submit(vector_search, query)<br>        fts_future = executor.submit(full_text_search, query)<br><br>    sponsored = get_sponsored_products()<br><br>    return {<br>        &quot;vector_results&quot;: vector_future.result(),<br>        &quot;fts_results&quot;: fts_future.result(),<br>        &quot;sponsored&quot;: sponsored<br>    }<br><br>start = time.time()<br>results = search_products(&quot;sneakers&quot;)<br>print(f&quot;Total time: {time.time() - start:.2f} seconds&quot;)</pre><h3>Output:</h3><pre>Total time: 5.00 seconds --- 😱</pre><h3>What’s Happening? 🤔</h3><p>You expect 3 seconds, but it takes 5! Moving out of the with block pauses execution until all tasks submitted inside it are complete. This causes the sponsored products call to start only after the first two tasks are done, delaying it by 2 seconds.</p><h3>The Fix ✅</h3><pre>def search_products_fixed(query):<br>    with ThreadPoolExecutor(max_workers=3) as executor:<br>        vector_future = executor.submit(vector_search, query)<br>        fts_future = executor.submit(full_text_search, query)<br>        sponsored = get_sponsored_products()<br>        return {<br>            &quot;vector_results&quot;: vector_future.result(),<br>            &quot;fts_results&quot;: fts_future.result(),<br>            &quot;sponsored&quot;: sponsored<br>        }<br><br>start = time.time()<br>results = search_products_fixed(&quot;sneakers&quot;)<br>print(results)<br>print(f&quot;Total time: {time.time() - start:.2f} seconds&quot;)</pre><h3>Output:</h3><pre>Total time: 3.00 seconds --- 🚀</pre><h3>Visualizing the Execution 🔍</h3><p>To better understand the difference between the before and after scenarios, here’s a graphical representation of how tasks are executed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*liH8vhvBtiU2TK_6" /></figure><h3>Key Takeaways 💡</h3><ol><li>Moving out of the with block waits for tasks to complete before proceeding.</li><li>Submit all parallel tasks inside the with block to avoid delays.</li><li>Plan workflows carefully for true parallelism.</li></ol><p>For more details, check the <a href="https://docs.python.org/3/library/concurrent.futures.html">official documentation</a>.</p><p>Have you faced similar surprises? Share your thoughts below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=508cc96f52b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Statistical Power: Exploring Z-Score Applications in the Workplace]]></title>
            <link>https://medium.com/@kswastik29/how-my-college-math-came-in-handy-at-work-64b7042eb214?source=rss-17649a99efa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/64b7042eb214</guid>
            <category><![CDATA[standard-deviation]]></category>
            <category><![CDATA[outlier-detection]]></category>
            <category><![CDATA[outliers]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[z-score]]></category>
            <dc:creator><![CDATA[Swastik]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 00:32:23 GMT</pubDate>
            <atom:updated>2025-01-29T06:22:58.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GcDarEY-jJTDnyc4f0ClGg.jpeg" /></figure><h3>Introduction</h3><p>Hey folks! Did you ever think those math classes in college were a waste of time? Well, I got a story for you. I ended up using some of that math to solve a real problem we had at work, making our website a bit smarter. Let’s dive into how a bit of math from the past helped us big time.</p><h3>The Challenge:</h3><p>Okay, so here’s what happens: When you type something like “I want wireless keyboards” on our site, we pull up the top 50 products that match your search. But we’re not just showing you these products straight away. We dive deeper into this list, storing all the details in a pandas DataFrame (yeah, the Python one). Then, we do a bit of magic with groupby on different columns — think price, brand, and most importantly, category — to figure out what facets or filters to show you. Sounds cool, right?</p><p>But here’s where we hit a snag. Not all of these top 50 products are always about keyboards. Imagine you’re all set to see different kinds of keyboards, but then, out of nowhere, a few mouse products show up in the mix. Yes, mouse, when you didn’t even ask for them. So now, we’re looking at a list like this:</p><ul><li>“Keyboards”: 20 products,</li><li>“Wireless Keyboards”: 15,</li><li>“Gaming Keyboards”: 10,</li><li>and unexpectedly, “Mouse”: 5 products.</li></ul><p>Our main puzzle was figuring out how to automatically filter out these misfits — like the mouse in our keyboard search — before we even start thinking about facets.</p><h3>Exploring Solutions:</h3><p><strong>Using the Median:</strong> Initially, we thought about the median — you know, the middle number in a sorted list. We figured if a category has more products than the median number of products across all categories, it stays. If not, it goes. It sounded better because it felt like we were making decisions based on some solid number. But here’s the catch: some categories were right on the edge, and we realized we were losing some good stuff just because of a technicality. Plus, what if most categories had similar numbers of products? We’d be back to square one.</p><h3>Realizing It’s All About Deviation:</h3><p>Before we found our solution, we had a lightbulb moment: our problem wasn’t just about counting products or picking categories over some arbitrary line. It was about understanding how much a category deviates from what’s typical in our top 50 products. Essentially, we were looking for a way to measure how far off a category is from the average or expected result for a search query. That’s when it clicked — this was a job for standard deviation and, by extension, Z-scores.</p><p>After realizing our problem could be addressed by understanding the variation in product category frequencies, we turned to a familiar concept from statistics: standard deviation (SD). SD helps us measure how spread out our data is. For our e-commerce challenge, it means figuring out how consistently product categories appear in the top 50 search results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBu0tl7QihudL-MtRJwYUw.jpeg" /><figcaption>What is the SD here? 😅</figcaption></figure><h3>Understanding Standard Deviation (SD):</h3><p>Standard deviation is a measure that tells us how spread out numbers are in a dataset. It’s particularly useful when deciding how consistent data is. For our e-commerce challenge, we needed to understand the spread of product frequencies across different categories to filter out the less relevant ones efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BwsgVvxvjleyhUbvtVLaGg.png" /><figcaption>Straight from ChatGPT 🙈</figcaption></figure><h3>Example Calculation with Keyboard Search Categories:</h3><p>Given:</p><ul><li>Keyboards: 20 products,</li><li>Wireless Keyboards: 15 products,</li><li>Gaming Keyboards: 10 products,</li><li>Mouse: 5 products</li></ul><h3>Steps:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-etfIz21sFTPdG4pnMBx0g.png" /></figure><p>So, the standard deviation is approximately 5.59 products, indicating on average, the product counts in each category vary by about 5.59 from the mean frequency (12.5 products). This helped us pinpoint which categories, like “Mouse,” significantly diverge from the typical distribution and should be filtered out.</p><h3>Choosing Z-Score: Beyond Standard Deviation</h3><p>Understanding the spread of our data with standard deviation was enlightening, but we needed a more precise tool to make decisions on filtering categories based on their relevance. This led us to the Z-score, a powerful statistic that doesn’t just measure variation, but quantifies how anomalous or typical a specific data point is relative to the average.</p><p><strong>Why Z-Score Makes Sense for Us:</strong></p><p>The Z-score converts each category’s frequency into a score that represents how many standard deviations it is away from the mean frequency. This standardization is crucial because it allows us to identify categories that are significantly less common — indicating they might not be what our users are actually searching for when they type in “wireless keyboards.”</p><p>Recalling Our Keyboard Example: Consider the product categories and their frequencies:</p><ul><li>Keyboards: 20 products</li><li>Wireless Keyboards: 15 products</li><li>Gaming Keyboards: 10 products</li><li>Mouse: 5 products</li></ul><p>Given our previously calculated mean (<em>μ</em>=12.5) and standard deviation (<em>σ</em>≈5.59), we can use the Z-score formula for each category:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Z5I9tJ3mX6O58XbQx2VcQ.png" /></figure><p>This Z-score tells us exactly how far “Mouse” deviates from the norm in a context where most categories cluster around keyboards. A negative Z-score, especially one like -1.34 (as calculated earlier), clearly flags “Mouse” as an outlier, not closely aligned with the main interest of our users.</p><p><strong>Setting the Threshold:</strong></p><p>By establishing a Z-score threshold, we could systematically decide which categories to keep and which to filter out. For instance, any category with a Z-score lower than -1 could be considered too rare within the context of the search query and thus excluded from the analysis. This method ensured that facets generated for user searches were as relevant and useful as possible, enhancing the overall search experience.</p><h3>Implementing the Z-Score Solution</h3><pre>def filter_categories_by_zscore(<br>    df: pd.DataFrame, z_threshold: float = -1<br>) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot;<br>    Filter categories in a DataFrame based on Z-score thresholds, ensuring top 5 products are retained.<br><br>    This function calculates the Z-scores of product categories based on their frequencies.<br>    Categories with Z-scores below the specified threshold are considered rare and are filtered out,<br>    except for categories of the top 5 products in the DataFrame, which are retained regardless of their Z-scores.<br><br>    Parameters:<br>    - df (pd.DataFrame): DataFrame containing product data. Must include a &#39;product_category&#39; column.<br>    - z_threshold (float): The Z-score threshold for filtering categories. Categories with Z-scores<br>      below this threshold will be excluded, except for categories of the top 5 products. Default is 0.<br><br>    Returns:<br>    - pd.DataFrame: A filtered DataFrame excluding products from categories below the Z-score threshold,<br>                    except for the top 5 products.<br>    &quot;&quot;&quot;<br><br>    # Ensure the DataFrame is not empty<br>    if df.empty:<br>        return df<br><br>    # Now select the top 5 from the unique products<br>    top_5_products = df.head(5)<br><br>    # Step 1: Calculate category frequencies<br>    category_counts = df[&quot;product_category&quot;].value_counts()<br><br>    # Step 2: Calculate the mean and standard deviation of category frequencies<br>    mean_freq = category_counts.mean()<br>    std_freq = category_counts.std()<br><br>    # Check if standard deviation is zero<br>    if std_freq == 0:<br>        # Standard deviation is zero, all categories have the same frequency.<br>        # Z-score filtering does not apply, and all categories are kept.<br>        return df<br><br>    # Step 3: Calculate Z-scores for each category<br>    z_scores = (category_counts - mean_freq) / std_freq<br><br>    # Identify categories that meet the Z-score threshold or are in the top 5 products<br>    keep_categories = z_scores[z_scores &gt;= z_threshold].index.tolist()<br><br>    # Add categories of the top 5 products to ensure they are retained<br>    top_5_categories = top_5_products[&quot;product_category&quot;].unique().tolist()<br>    final_categories = list(set(keep_categories + top_5_categories))<br><br>    # Filter the DataFrame to include only the desired categories<br>    filtered_df = df[df[&quot;product_category&quot;].isin(final_categories)]<br><br>    return filtered_df</pre><p>We’ve broken the rule in one instance by including products with Z-scores less than the threshold, and here’s why:</p><p><strong>Preservation of Top 5 Unique Products:</strong> In our scenario, the top 5 products hold significant importance as they are highly relevant to the user’s query. These products have demonstrated a strong association with the user’s search intent, indicating their high relevancy. It’s common for users to search for specific products that may be rare in our store, resulting in only a few instances being present in the dataset.</p><p>In such scenarios, where certain products are scarce but crucially relevant to the user’s search, it becomes imperative to preserve them in the search results. Even if the category to which these products belong falls below the Z-score threshold, indicating rarity, these top 5 products should not be overlooked. By retaining these products, we ensure that the search results remain aligned with the user’s intent, providing a more comprehensive and accurate representation of available options.</p><h3>Benefits and Considerations</h3><p>The introduction of Z-scores significantly improved the accuracy and relevance of our search results. However, selecting the optimal threshold and interpreting the scores required careful consideration and understanding of the dataset’s distribution.</p><p>Before wrapping up, let’s address a few confusions or doubts that may have arisen during our discussion.</p><h3>Understanding the Link: Standard Deviation and Z-Scores</h3><p>While we’ve seen how both standard deviation and Z-scores play pivotal roles in our data analysis journey, it’s crucial to understand how they are related yet serve different purposes. Let’s demystify this with our keyboard and mouse product categories example.</p><p><strong>Standard Deviation</strong> — The Measure of Spread: Standard deviation gives us a sense of how spread out the product frequencies are from the average frequency. In our example, the SD tells us that, on average, the number of products in each category varies by about 5.59 products from the mean (12.5 products).</p><p><strong>Z-Score </strong>— The Measure of Position: Z-score takes this a step further by not only considering the spread but also pinpointing the exact position of a category’s frequency relative to the average. It tells us how many standard deviations away a category’s frequency is from the mean. For instance, the “Mouse” category, with a Z-score of approximately -1.34, is about 1.34 standard deviations below the mean frequency.</p><p><strong>How They Relate:</strong></p><ul><li>Standard deviation is a building block for calculating Z-scores. Without knowing the average spread (SD) of our data, we wouldn’t be able to standardize our individual data points (frequencies) into Z-scores.</li><li>While SD gives us a general idea of variability, Z-scores provide a standardized way to compare that variability across different datasets or within different parts of the same dataset.</li></ul><p><strong>The Key Difference:</strong></p><ul><li>Standard Deviation tells us about the variability or spread of our dataset.</li><li>Z-Score tells us the relative position of each data point within that spread, in a standardized format.</li></ul><p>In practice, while the standard deviation helped us grasp the overall spread in product category frequencies, the Z-score enabled us to objectively identify which categories were outliers (like our “Mouse” category) and needed to be filtered out for a more relevant search result.</p><h3>Navigating Z-Scores: From Zero to Outliers</h3><p>Z-scores offer a standardized way to gauge how each product category’s frequency compares to the average, but what do specific scores like 0, -1, and 1 tell us? Understanding these scores is key to making informed decisions about filtering product categories.</p><p><strong>Z-Score of 0:</strong></p><ul><li>A Z-score of 0 means the category’s frequency is exactly at the mean of all categories’ frequencies. It signifies an average level of relevance; the category is as common as the typical category in search results. For instance, if “Gaming Keyboards” had a Z-score of 0, this would indicate that its presence in search results is perfectly average — not particularly rare or common.</li></ul><p><strong>Z-Score of -1:</strong></p><ul><li>A Z-score of -1 signifies that a category’s frequency is one standard deviation below the mean. Categories at this score are on the edge of being considered less relevant because they’re less common than what’s typical. Crossing below this threshold (-1) into more negative territory marks a category as increasingly irrelevant or rare in the context of the search. It’s the starting point where we begin to question a category’s relevance to the user’s query.</li></ul><p><strong>Z-Score of 1:</strong></p><ul><li>Conversely, a Z-score of 1 indicates that a category’s frequency is one standard deviation above the mean. This score points to higher relevance and commonality, suggesting the category is notably more prevalent in search results than average. Categories scoring around 1 or higher are deemed especially relevant and are prioritized in search facets and results.</li></ul><h3>The Practical Impact of Z-Score Thresholds:</h3><p>By setting a threshold at -1, we strategically filter out categories that are significantly less common, ensuring that the search results focus on what’s genuinely relevant:</p><ul><li><strong>Above -1 (including 0 and 1):</strong> Categories with Z-scores in this range are considered relevant. They either match the average relevance (0), are somewhat more common (up to +1), or are significantly common (+1 and beyond), all of which indicates their importance to the search context.</li><li><strong>Below -1:</strong> Categories that fall below this threshold are viewed as outliers. They’re significantly less common than the average, suggesting they may not be what the user is looking for.</li></ul><p><strong>Example in Action:</strong></p><ul><li>“Mouse” with a Z-score of -1.34 are filtered out as irrelevant for a keyboard search.</li><li>“Gaming Keyboards” at 0 would be considered average in relevance, likely included in search results.</li><li>“Wireless Keyboards” scoring +1.25 are highlighted as particularly relevant, ensuring their prominence in search facets.</li></ul><h3>Conclusion</h3><p>Adopting Z-scores into our categorization process not only refined our search results but also highlighted the power of applying statistical methods to e-commerce challenges, blending theoretical knowledge with practical application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64b7042eb214" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common mistakes to avoid when using @Transactional in Spring]]></title>
            <link>https://medium.com/@kswastik29/common-mistakes-to-avoid-when-using-transactional-in-spring-2ba17a76ff1f?source=rss-17649a99efa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ba17a76ff1f</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Swastik]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 10:48:11 GMT</pubDate>
            <atom:updated>2024-09-03T16:23:02.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt=":)" src="https://cdn-images-1.medium.com/max/1024/1*HFHqbJ2POIu3IplSJLPgew.jpeg" /></figure><p>In the world of Spring Framework, managing transactions using @Transactional is a powerful feature. However, with great power comes great responsibility. Misunderstandings and misapplications of this annotation can lead to subtle bugs and data inconsistencies. Today, we&#39;re going to uncover some common pitfalls and how to avoid them.</p><h3>Mistake #1: Your @Transactional is silently getting ignored</h3><p>A common oversight in Spring applications is using the @Transactional annotation on private methods or invoking it from within the same bean, which leads to the annotation being silently ignored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwVzZ-hScYAUDWUU-8tQ_w.jpeg" /><figcaption>@Transaction getting ignored</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QxCNfvQ7tWjn0ccmcPi8JQ.jpeg" /><figcaption>The right way of using @Transactional on methods</figcaption></figure><p>This holds for various other annotations such as <a href="https://spring.io/guides/gs/async-method/"><strong>@<em>Async</em></strong></a> and <a href="https://spring.io/guides/gs/caching/"><strong><em>@Cacheable</em></strong>.</a> For more details refer to <a href="https://docs.spring.io/spring-framework/docs/3.0.x/spring-framework-reference/html/aop.html#aop-understanding-aop-proxies">Aspect Oriented Programming with Spring</a></p><p>Before diving into the next common mistake, let’s examine a typical example of @Transactional in action, as seen in this AccountService implementation in a Spring application.</p><p><strong>Account.java</strong></p><pre>@Entity<br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Table(name = &quot;account&quot;)<br>public class Account{<br><br>  @Id<br>  @GeneratedValue(strategy = GenerationType.IDENTITY)<br>  private Long id;<br><br>  private String ownerName;<br>  private BigDecimal balance;<br><br>}</pre><p><strong>AccountService.java</strong></p><pre>@Service<br>public class AccountService {<br><br>  @Autowired private AccountRepository accountRepository;<br><br>  @Transactional<br>  public void transferMoney(Long fromAccountId, Long toAccountId, BigDecimal amount) {<br>    try {<br><br>      Account fromAccount =<br>          accountRepository<br>              .findById(fromAccountId)<br>              .orElseThrow(<br>                  () -&gt; new Exception(&quot;Account not found: &quot; + fromAccountId));<br><br>      Account toAccount =<br>          accountRepository<br>              .findById(toAccountId)<br>              .orElseThrow(() -&gt; new Exception(&quot;Account not found: &quot; + toAccountId));<br><br>      if (fromAccount.getBalance().compareTo(amount) &lt; 0) {<br>        throw new Exception(&quot;Insufficient balance in account: &quot; + fromAccountId);<br>      }<br><br>      fromAccount.setBalance(fromAccount.getBalance().subtract(amount));<br>      accountRepository.save(fromAccount);<br><br>      // Simulate an error in updating the recipient&#39;s account<br>      if (toAccount.getId().equals((long) -1)) {<br>        throw new Exception(&quot;Error in processing recipient account&quot;);<br>      }<br><br>      toAccount.setBalance(toAccount.getBalance().add(amount));<br>      accountRepository.save(toAccount);<br>    } catch (Exception e) {<br>      log.error(&quot;Error occurred while transferring money ...&quot;);<br>    }<br>  }<br>}</pre><p><em>Here’s an oversimplified example illustrating how @Transactional operates:</em></p><pre>import java.sql.Connection;<br>import java.sql.SQLException;<br><br>public class TransactionExample {<br><br>    public void executeTransaction() {<br>        // Get a database connection<br>        Connection connection = dataSource.getConnection();<br><br>        try (connection) {<br>            // Begin the transaction<br>            connection.setAutoCommit(false);<br><br>            // Execute SQL statements here<br>            // Example: INSERT, UPDATE, or DELETE operations<br><br>            // Commit the transaction<br>            connection.commit();<br>        } catch (SQLException e) {<br>            // Roll back the transaction in case of an error<br>            connection.rollback();<br>        }<br>    }<br>}</pre><p>The @Transactional annotation marks the start and end of a transaction in a Spring application. When a method is annotated with @Transactional, the transaction starts as soon as the method begins and ends when the method is done. This way, everything done in the method either all works together or doesn&#39;t happen at all, keeping the data safe and consistent.</p><p>With this background in place, we’re now ready to delve into common Mistake #2</p><h3>Mistake #2: Catching Exceptions Inside a @Transactional Method</h3><p>A crucial aspect of transaction management in Spring that’s often misunderstood involves the handling of exceptions within methods annotated with @Transactional. When exceptions are caught and handled inside such methods, it can inadvertently prevent the transaction from being rolled back, potentially leading to unexpected data states.</p><h4>Why Does This Happen?</h4><p>Spring’s @Transactional mechanism is designed to roll back transactions in the event of runtime exceptions. The transaction manager looks for these unhandled exceptions to trigger a rollback. However, if an exception is caught within the method and not rethrown, the transaction manager remains unaware of any issues, and as a result, the transaction is not rolled back but rather committed.</p><p>Now let’s modify our above code to throw the error so that we can rollback</p><pre>@Service<br>public class AccountService {<br><br>  @Autowired private AccountRepository accountRepository;<br><br>  @Transactional<br>  public void transferMoney(Long fromAccountId, Long toAccountId, BigDecimal amount) {<br>    try {<br>      // ... fetch accounts<br><br>      fromAccount.setBalance(fromAccount.getBalance().subtract(amount));<br>      accountRepository.save(fromAccount);<br><br>      // Simulate an error in updating the recipient&#39;s account<br>      if (toAccount.getId().equals((long) -1)) {<br>        throw new Exception(&quot;Error in processing recipient account&quot;);<br>      }<br><br>      toAccount.setBalance(toAccount.getBalance().add(amount));<br>      accountRepository.save(toAccount);<br>    } catch (Exception e) {<br>      log.error(&quot;Error occurred while transferring money ...&quot;);<br>      throw e;<br>    }<br>  }<br>}</pre><p>But wait, there is a catch: this still doesn’t make the transaction roll back because, by default, <strong><em>“The transaction will roll back on RuntimeException and Error but not on checked exceptions.”</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CzAEJeB4R-xnIPOo.png" /><figcaption>Exception Hierarchy in Java — please don’t give copyrights :)</figcaption></figure><p>To override this default behaviour, we have to set the rollbackFor property with the class of exception that we want to rollback for. Now the function will look like below:</p><pre>@Transactional(rollbackFor = Exception.class)<br>public void transferMoney(Long fromAccountId, Long toAccountId, BigDecimal amount) throws Exception {<br>  try {<br>    // ... transaction fails ...<br>  } catch (Exception e) {<br>    log.error(&quot;Error occurred while transferring money ...&quot;);<br>    throw e;<br>  }<br>}</pre><h3><strong>Conclusion</strong></h3><p>🎉 That’s a wrap! Remember, correctly using @Transactional in Spring involves two key practices: ensuring it&#39;s applied on public methods or external bean calls to avoid being ignored, and setting the rollbackFor attribute for precise transaction rollback control. Mastering these aspects is crucial for robust transaction management and maintaining data integrity in your applications.</p><p>If you found this interesting, you might also enjoy my previous piece on <a href="https://medium.com/@kswastik29/common-mistakes-to-avoid-when-using-async-in-spring-1eef0e8d15fb">Common mistakes to avoid when using @Async in Spring.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ba17a76ff1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common mistakes to avoid when using @Async in Spring]]></title>
            <link>https://medium.com/@kswastik29/common-mistakes-to-avoid-when-using-async-in-spring-1eef0e8d15fb?source=rss-17649a99efa2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1eef0e8d15fb</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Swastik]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 10:42:33 GMT</pubDate>
            <atom:updated>2024-09-03T16:23:24.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGfydPzP3buF46soYAxp4Q.jpeg" /></figure><p>Spring is a very powerful framework for building Java applications. It hides most of the complexities, such as managing database transactions with <a href="http://twitter.com/Transactional">@Transactional</a>, running asynchronous code with <a href="http://twitter.com/Async">@Async</a>, consuming Kafka messages with just <a href="http://twitter.com/KafkaListener">@KafkaListener</a>, and so on, which makes the life of a developer easy.</p><p>In this blog, I’ll be going through @Async annotation and how we can make use of it to run any code block asynchronously. Just by adding @Async to the method that we want to run asynchronously, that method will be executed in a separate thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*NsIAlOGsTZJrjitX7akIUw.gif" /><figcaption>Please ignore, just to attract Java audience</figcaption></figure><p><strong>Sample Code</strong></p><pre>@RestController<br>public class AuthenticationController {<br><br>  @Autowired<br>  private MailService mailService;<br><br>  @PostMapping(&quot;/sing-up&quot;)<br>  public ResponseEntity&lt;Boolean&gt; singUp(@RequestBody UserDetails userDetails) {<br>    boolean isSuccess = authenticationService.createuser(userDetails);<br>    if (isSuccess) {<br>      mailService.sendVerificationEmail(userDetails.getEmail());<br>    }<br>    return new ResponseEntity&lt;&gt;(isSuccess, HttpStatus.OK);<br>  }<br>}</pre><pre>@Service<br>public class MailService {<br><br>  @Async<br>  public void sendVerificationEmail(String email) {<br>    System.out.println(&quot;Sending verification email to email: &quot; + email);<br>  }<br>}</pre><pre>@SpringBootApplication<br>@EnableAsync<br>public class ThreadsApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(ThreadsApplication.class, args);<br> }<br><br> @Bean<br> public TaskExecutor taskExecutor() {<br>  ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();<br>  threadPoolTaskExecutor.setThreadNamePrefix(&quot;Async-&quot;);<br>  threadPoolTaskExecutor.setCorePoolSize(2);<br>  threadPoolTaskExecutor.setMaxPoolSize(6);<br>  threadPoolTaskExecutor.setQueueCapacity(5);<br>  return threadPoolTaskExecutor;<br> }<br><br>}</pre><p>Here for now let’s concentrate only on first 2 code blocks, will come to 3rd code block later in the same blog.</p><p>When a request is received for creating a user, we call the createUser() method of some class to register the user, and it returns the registration status. If registration is successful, we want to send a verification email to the user; this is where we can make use of @Asyncannotation. Because MailService can be slow due to various reasons and it is better to return to frontend as quickly as possible so that end user don’t feel slowness.</p><p>Let’s start discussing the mistakes that we may make here.</p><p><strong>Mistake 1: Not following rules of @Async</strong></p><p>In order to make @Async annotation work properly we have to follow 2 major rules</p><ol><li>Method annotated with @Async should be public</li><li>Method annotated with @Async should be called from different class, i.e calling async method within the same class doesn’t work</li></ol><p>For more details refer <a href="https://docs.spring.io/spring-framework/docs/3.0.x/spring-framework-reference/html/aop.html#aop-understanding-aop-proxies">Aspect Oriented Programming with Spring</a></p><p>Now, let’s have a look at what’s going on in our third code block <strong>— this is where the magic and confusion begin.</strong></p><p>In order for @Async to work, we need to add @EnableAsyncannotation to any of the configuration classes; here, we have added it to our main class annotated with @SpringBootApplication.</p><p>Along with this, spring also expects us to provide bean which defines thread pool-related details. According to spring documentation</p><blockquote>By default, Spring will be searching for an associated thread pool definition: either a unique <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/task/TaskExecutor.html">TaskExecutor</a> bean in the context, or an <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/Executor.html">Executor</a> bean named &quot;taskExecutor&quot; otherwise. If neither of the two is resolvable, a <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/task/SimpleAsyncTaskExecutor.html">SimpleAsyncTaskExecutor</a> will be used to process async method invocations.</blockquote><p>Great, we have also provided the bean taskExecutor with thread pool-related details specified, Now you might be thinking, &quot;What is the magic or confusion here?&quot; Let’s take a look at the taskExecutor bean we have defined.</p><pre>@Bean<br> public TaskExecutor taskExecutor() {<br>  ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();<br>  threadPoolTaskExecutor.setThreadNamePrefix(&quot;Async-&quot;);<br>  threadPoolTaskExecutor.setCorePoolSize(2);<br>  threadPoolTaskExecutor.setMaxPoolSize(6);<br>  threadPoolTaskExecutor.setQueueCapacity(5);<br>  return threadPoolTaskExecutor;<br> }</pre><p>In the first line, we are creating an instance of ThreadPoolTaskExecutor, which is a wrapper provided by Spring on top of <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html">ThreadPoolExecutor</a>. The second line doesn’t need any explanation.</p><p>The third, fourth, and fifth lines are more important because they lead to our Mistake 2.</p><p><strong>Mistake 2: Not understanding how </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html"><strong>ThreadPoolExecutor</strong></a><strong> is implemented</strong></p><p><strong>Assumption that we make looking into the above code</strong>: Spring will create new threads for each task until MaxPoolSize is reached, and for upcoming tasks if the thread count is greater than or equal to MaxPoolSize, the tasks are queued up to QueueCapacity, and any other further tasks are ignored after the QueueCapacity and MaxPoolSize limits are reached.</p><p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html"><strong>ThreadPoolExecutor’s</strong></a><strong> way of implementation: </strong>New threads are created for each task until CorePoolSize is reached, after which the tasks are queued up to QueueCapacity, and once QueueCapacity is reached, new threads are created up to MaxPoolSize, and when all three parameters reach their limits, tasks will be rejected.</p><p>I know you have not understood anything. To make it more clear, I’ve planned to explain the above concept in two ways.</p><ol><li>Using code</li><li>Using Animation — My favourite way</li></ol><p><strong>Understanding through Code</strong></p><pre>@RestController<br>public class ThreadController {<br><br>  @Autowired<br>  private ThreadService threadService;<br><br><br>  @GetMapping(&quot;/async/{number}&quot;)<br>  public void async(@PathVariable long number) {<br>    try {<br>      threadService.printNumber(number);<br>    } catch (RejectedExecutionException e) {<br>      System.out.println(<br>          &quot;Rejecting task since queue is full and no threads are free for task number: &quot; + number);<br>    }<br>  }<br><br><br>  @PostConstruct<br>  public void init() throws InterruptedException {<br>    for (int i=1; i&lt;=11; i++) {<br>      threadService.printNumber(i);<br>      Thread.sleep(100);<br>    }<br>  }<br>}</pre><pre>@Service<br>public class ThreadService {<br><br>  @Async<br>  public void printNumber(long num) {<br>    System.out.println(num);<br>    try {<br>      Thread.sleep(60000);<br>    }<br>    catch (InterruptedException e) {<br>      System.out.println(&quot;Error while executing sleep in Thread for task: &quot; + num);<br>    }<br>  }<br>}</pre><p>Here I’m triggering the @Async method printNumber inside the init() method annotated with @PostConstruct; when the app starts, this init() method will be called. The code just loops over 11 iterations and calls the printNumber() method, and inside that method I’ve added a sleep of 1 minute. When app starts and when we see below log I’ll hit API <a href="http://localhost:8082/async/100">http://localhost:8082/async/100</a> to illustrate how tasks will be rejected when all three parameters (CorePoolSize, MaxPooSize and QueueCapacity) have reached their limits.</p><pre>2023-02-26 15:21:48.959  INFO 64720 --- [           main] com.async.async.AsyncApplication         : Started AsyncApplication in 0.914 seconds (JVM running for 1.126) </pre><p><strong>Output </strong>— When we follow above steps we get output in below order</p><pre>1<br>2<br>8<br>9<br>10<br>11<br><br>2023-02-26 15:26:10.734  INFO 64785 --- [           main] com.async.async.AsyncApplication         : Started AsyncApplication in 2.035 seconds (JVM running for 2.254)<br><br>Rejecting task since queue is full and no threads are free for task number: 100<br>3<br>4<br>5<br>6<br>7</pre><p>As we can see, first tasks 1 and 2 are executed, which are because of the CorePoolSize — 2, and after that, tasks 3, 4, 5, 6, &amp; 7 are queued and QueueCapacity of 5 is reached, after that, new tasks 8, 9, 10 &amp; 11 are assigned new threads up to MaxPoolSize — 6 here, though MaxPoolSize is 6 only 4 new threads can be created because 2 threads are taken initially by task-1 and task-2 and they are still not completed (remember we added sleep of 1min, that’s why it is not completed).</p><p>Now all three parameters have reached the limit, and when I hit the API at <a href="http://localhost:8082/async/100,">http://localhost:8082/async/100,</a> a RejectedExecutionException is raised. We are handling that exception and printing something, which is why we are seeing log Rejecting task since queue is full and no threads are free for task number: 100 after 1, 2 8, 9, 10, 11 are printed.</p><p>Finally, after one minute, threads will be free, tasks are dequeued from the queue, and each is assigned a thread, because of which we can see that 3, 4, 5, 6, 7 are printed.</p><p><strong>Understanding through Animation </strong>— This is my favourite part, instead of reading 100’s of lines spending 50s is enough to understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*D_yBuL5vMrLGmso7YVPufQ.gif" /></figure><p>So be careful if you are expecting tasks to be executed in the order, you may have to play around with QueueCapacityparameter</p><p>This is my first blog, and I might have made lots of mistakes. Please let me know if there are any mistakes in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1eef0e8d15fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>