<?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 Yudum Paçin on Medium]]></title>
        <description><![CDATA[Stories by Yudum Paçin on Medium]]></description>
        <link>https://medium.com/@yudumpacin?source=rss-3bffaee71ddd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bRyZNX-ydXUAYo5s-d-E3Q.jpeg</url>
            <title>Stories by Yudum Paçin on Medium</title>
            <link>https://medium.com/@yudumpacin?source=rss-3bffaee71ddd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:47:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yudumpacin/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[RAG Evaluation Challenges and Practical Insights]]></title>
            <link>https://medium.com/yapi-kredi-teknoloji/rag-evaluation-challenges-and-practical-insights-e8f35a4cd93b?source=rss-3bffaee71ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8f35a4cd93b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rag-evaluation]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Yudum Paçin]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 15:15:57 GMT</pubDate>
            <atom:updated>2026-04-30T15:15:57.452Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bx0-CMkV11If3cHuX589IA.jpeg" /></figure><p>Retrieval-Augmented Generation (RAG) is an architecture that enables Large Language Models (LLMs) to generate more reliable, context-aware responses by retrieving up-to-date and proprietary information from external sources rather than relying only on static training data.</p><p>As RAG systems move from prototypes to production, testing becomes essential. In production environments, we must ensure consistent quality, detect regressions and build confidence in system behavior.</p><p>In traditional software systems, the same input produces the same output. This determinism makes testing straightforward: you define expected results, write assertions and detect regressions when something breaks.</p><p>RAG breaks this assumption. Evaluation shifts from deterministic pass/fail checks to score-based assessments, where results must be interpreted rather than strictly asserted.</p><figure><img alt="Figure 1: Traditional Software Test Case vs Rag Evaluation Test Case" src="https://cdn-images-1.medium.com/max/982/1*QScXGt8LOITUAlyi3LW3nA.png" /><figcaption>Traditional Software Test Case vs Rag Evaluation Test Case</figcaption></figure><p>In this blog, we explore how to evaluate RAG systems in practice, outline the core challenges of RAG evaluation and share the practical approaches we have used to address them.</p><p><strong>What is RAG Evaluation and What is Not</strong></p><p>At first glance, RAG evaluation may seem similar to <strong>reference-based</strong> evaluation, where outputs are compared against reference answers using traditional NLP metrics such as ROUGE or BLEU. However, these metrics primarily rely on n-gram overlap and lexical similarity, and often fail to capture true semantic similarity. More importantly, they do not assess whether the response is grounded in the retrieved context.</p><p>RAG systems are not monolithic black-box models, but modular systems composed of two main components:</p><ul><li><strong>Retrieval</strong>: retrieving relevant documents or text chunks from a knowledge base</li><li><strong>Generation</strong>: generating a response using the retrieved context and the user query</li></ul><p>Because of this architecture, evaluating only the final output is not sufficient. Errors can originate from either retrieval or generation, and each component must be evaluated separately.</p><p>A commonly used framework for this is the RAG Triad, which evaluates three key aspects of the system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*RkAJOdjElw5S1BS4SugzbQ.png" /><figcaption>RAG Triad, <em>Source: TruLens RAG Triad framework</em></figcaption></figure><ul><li><strong>Faithfulness:</strong> whether the generated response is grounded in the retrieved context</li><li><strong>Answer Relevancy:</strong> whether the response addresses the user query</li><li><strong>Context Relevancy:</strong> whether the retrieved context is relevant to the query</li></ul><p>By checking multiple metrics, you can identify where the system fails.</p><p>For example:</p><ul><li>If <strong>answer relevancy</strong> is low, you may need to revise your prompt instructions</li><li>If <strong>context relevancy</strong> is low, you should check your retrieval pipeline</li><li>If <strong>faithfulness</strong> is low, you should revisit your prompt design to ensure the model uses the retrieved context properly</li></ul><p>While these metrics form the foundation of RAG evaluation, they are often not sufficient in real-world systems. As system complexity increases, additional evaluation metrics are required. There are several open-source frameworks providing implementations of these metrics and allow customization based on specific use cases.</p><p><strong>Ragas vs Deepeval</strong></p><p>Ragas and DeepEval are two of the most widely used open-source frameworks for evaluating Retrieval-Augmented Generation (RAG) systems.</p><p>Ragas was introduced in 2023 with the paper <em>“RAGAS: Automated Evaluation of Retrieval-Augmented Generation”</em>, focusing on reference-free evaluation and gaining early recognition, including mentions at OpenAI DevDay. DeepEval, in contrast, adopts a test-driven approach, making it easier to integrate evaluation into development workflows.</p><p>Both frameworks rely on the LLM-as-a-judge paradigm and offer similar core capabilities. As highlighted in the <a href="https://deepeval.com/blog/deepeval-vs-ragas">DeepEval vs Ragas blog</a>, their metric implementations are highly similar, with many of Ragas metrics re-implemented in DeepEval. As a result, the choice between the two largely depends on specific use cases and integration needs.</p><p>The same blog also notes that, as of 2024, DeepEval extends these capabilities with features such as built-in explainability (reasoning for scores) and a simpler approach to custom LLM usage, which was harder to integrate in Ragas at the time.</p><p>Based on our experience, DeepEval tends to be easier to integrate into existing testing workflows and offers more flexibility when defining custom metrics. However, both frameworks are actively evolving, and the gap between them is narrowing, choice is depended on specific use cases rather than clear technical differences.</p><p><strong>LLM-as-a-judge</strong></p><p>LLM-as-a-Judge is an approach where a language model is used to evaluate the outputs of another system and produce a judgment or score. In the context of RAG systems, the LLM acts as an evaluator that assesses the generated answer based on predefined criteria. However, simply asking whether an answer is correct is not enough, as LLM responses can vary across runs. To reduce this variability, evaluation is typically structured using well-defined prompts and scoring schemes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*NTY9a7krspA7zjuLqOvjzA.png" /><figcaption>Measuring the Faithfulness Metric,<strong> </strong><em>Generated via Nano Banana 2</em></figcaption></figure><p><strong>Example: Faithfulness Metric</strong></p><p>In DeepEval, the faithfulness metric is measured using three inputs:</p><ul><li>Actual output (generated answer)</li><li>Input (query)</li><li>Retrieved context</li></ul><p>Measurement is done by following steps:</p><ul><li>The judge LLM extracts claims from the generated answer</li><li>The judge LLM assigns a verdict (e.g., yes / no / idk) for each claim based on it is attributed from retrieved context</li><li>The final score is computed based on these verdicts as</li></ul><p>Number of supported claims (yes verdicts) / Total number of claims</p><p>A higher score indicates that the answer is more grounded in the retrieved context and less likely to contain hallucinations.</p><p>The FaithfulnessMetric in DeepEval relies on prompt templates to extract the response into claims and assign verdicts. You can define a customized FaithfulnessMetric by following the original implementation on the GitHub page below and adapting it to your needs.</p><p><a href="https://github.com/confident-ai/deepeval/blob/main/deepeval/metrics/faithfulness/faithfulness.py">deepeval/deepeval/metrics/faithfulness/faithfulness.py at main · confident-ai/deepeval · GitHub</a></p><p>The code below shows the evaluation of a customized metric, TurkishFaithfulnessMetric.</p><pre>from deepeval.test_case import LLMTestCase<br>from deepeval import evaluate<br>from customized_metrics import TurkishFaithfulnessMetric #customized metric implementation<br>metric = TurkishFaithfulnessMetric(<br>threshold=0.5, # You can tune the threshold<br>model=judge_llm, # Define your judge LLM by implementing the BaseLLM interface<br>async_mode=True # Enable async mode<br>)<br>test_case = LLMTestCase(<br>input=&quot;Doğum izni kaç gündür?&quot;,<br>actual_output=&quot;Verilen metne göre doğum izni 16 haftadır.&quot;,<br>retrieval_context=[<br>&quot;kadın çalışanlara doğum öncesinde 8, doğum sonrasında 8 hafta olmak üzere toplam 16 hafta ücretli izin veriliyor.&quot;<br>]<br>)<br>result = evaluate(<br>test_cases=[test_case],<br>metrics=[metric],<br>)<br>print(result)</pre><p>In the default metric implementation, the model’s response is parsed into a structured JSON format. Since the FaithfulnessMetric expects a strict schema, JSON parsing errors may occur when the output is not properly formatted by the judge LLM.</p><p>In the customized metric implementation, an additional processing layer is introduced to handle LLM outputs more robustly.</p><pre>res = await self.model.a_generate(prompt)<br>data = json_repair(res) #Additional json repair function</pre><p>Also, note that DeepEval metrics run asynchronously by default. Async mode enables concurrent LLM calls and significantly improve performance.</p><p>In the following sections, we outline key challenges encountered in practice and share practical insights and lessons learned from evaluating a real world RAG system.</p><p><strong>Creating a Test Dataset</strong></p><p>The test dataset used to evaluate our RAG system consists of a query, golden (correct) documents, retrieved documents, retrieved context, generated answers and predefined correct answers. Creating a high-quality test dataset is often the most challenging part of the evaluation process.</p><p>The main difficulty lies in the nature of the knowledge base. In our case, and as in most real-world systems, the knowledge base is not static. New documents are continuously added, existing ones are updated and historical documents are retained. As a result, a document that serves as the correct source at one point in time may become outdated later. This requires continuous updates to the evaluation dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*Nf6JK7Yfzl5kswEkPGijkg.png" /><figcaption>Reruning the evaluations,<strong> </strong><em>Source: KC Green (Gunshow Comic)</em></figcaption></figure><p>Another challenge is coverage. The dataset should not only include simple, single-turn queries but also reflect real user behavior. However, user behavior is often difficult to anticipate in advance. For example, users may use keyword-based searches instead of full queries and ask less explicit questions than expected.</p><p>For example:</p><pre>[User] konut kredisine nasıl başvurulur?<br>[System] Konut kredisine başvurmak için…<br>[User] ya ikinci eviyse?</pre><p>These short queries, multi-turn scenarios must be included in the dataset to properly evaluate whether the system maintains consistency or starts hallucinating.</p><p>DeepEval and Ragas also provide utilities to generate test datasets for both single-turn and multi-turn conversations from raw documents (e.g., PDFs). This helps reduce manual effort, but the generated test data still require careful validation and comparison with real scenarios.</p><p><strong>Using LLM as a Judge</strong></p><p>When using LLMs as evaluators, the main challenge is variability across runs, where the same inputs can produce different evaluation results. To reduce this, we set the <strong>temperature </strong>to 0 and <strong>top-p </strong>to 1.0. Setting the temperature to 0 leads to greedy decoding, where the most probable token is selected at each step, while top-p = 1.0 ensures that all candidate tokens are considered without filtering. These settings make the outputs more consistent across runs, but they do not guarantee identical outputs across runs. They also do not necessarily improve the correctness of the evaluations. As a result, if the judge LLM produces an incorrect verdict in the first run, it may consistently produce the same incorrect decision under these settings.</p><p>Another challenge is structured output generation. DeepEval expects the LLM to return results in JSON format. In practice, however, LLMs may fail to produce valid JSON. To mitigate this, several approaches are applied:</p><ul><li>providing few-shot examples and customizing prompts</li><li>adding a JSON repair logic based on observed errors in the LLM output</li></ul><p>Despite these improvements, structured output generation remains a practical challenge.</p><p>Another practical consideration is the trade-off between latency and evaluation quality. Each evaluation metric typically requires multiple LLM calls — for example, one to extract claims and another to produce a verdict — which can significantly increase evaluation time, especially for long contexts. Setting a lower limit for <strong>max_tokens</strong> — the maximum number of tokens the model can generate — can help reduce latency, but often results in incomplete outputs and less reliable evaluation results.</p><p>We use a locally deployed Qwen3–30B-A3B model as the evaluator. Although larger and more capable proprietary models (e.g., GPT-4 or Claude) could potentially mitigate some of these challenges, they were not considered due to restrictions on sharing domain-specific data with external services.</p><p><strong>Tuning Evaluation Metrics</strong></p><p>When evaluation metrics are used with their default settings, the results may not always align well with non-English (e.g., Turkish), domain-specific documents as in our case. For this reason, metrics often need to be tuned, and in some cases, custom metrics should also be added.</p><p>The table below summarizes the metrics we used, including what they measure, how they are computed and how they were tuned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dw1Jdx8-RzTOu-LntGKXw.png" /></figure><p>In practice, most test sets only include document-level references and lack chunk-level annotations. For this reason, we used the <strong>Document Accuracy</strong> metric together with <strong>Contextual Relevancy</strong> and <strong>Contextual Recall</strong> to better assess whether the retrieved context corresponds to the correct part of the document. However, <strong>Contextual Relevancy</strong> tends to perform poorly with large chunks, where only a small portion is relevant and the rest introduces noise (e.g., FAQ-style documents). For this reason, lower thresholds were used.</p><p>Retrieval metrics evaluate the retrieve system as a whole, but it is useful to separate embedding retrieval from reranking performance. While <strong>contextual precision</strong> measures ranking quality using LLM-as-a-Judge, it can be computationally expensive. Simpler metrics like <strong>MRR</strong> can be used to measure the reranker success.</p><p>Our results show that the majority of errors in RAG evaluation originate from the retrieval stage. When the model is faced with missing, insufficient, or noisy context, the critical question becomes whether it can appropriately answer as “I ‘don’t know” or whether it generates incorrect answers based on irrelevant information.</p><p>Two additional metrics, introduced in the study <a href="https://arxiv.org/pdf/2309.01431"><em>Benchmarking Large Language Models in Retrieval-Augmented Generation</em></a><em>, (Chen et al., 2023)</em>, address this issue:</p><p><strong>Noise Vulnerability,</strong> which measures whether the model fails in the presence of irrelevant or noisy context.</p><p><strong>Negative Rejection,</strong> which measures whether the model can say “I don’t know” when the available information is insufficient.</p><p>Ragas also includes an implementation of the <strong>Noise Sensitivity</strong> metric, which evaluates how frequently a system generates incorrect responses when using both relevant and irrelevant retrieved documents. This metric was first introduced in the <a href="https://arxiv.org/html/2408.08067v1">RAGChecker</a>, (Ru et al., 2024).</p><p>If all of these metrics do not fully address your evaluation needs, you can define a custom metric using <a href="https://deepeval.com/docs/metrics-llm-evals">G-Eval</a> by providing the expected and generated outputs along with your specific evaluation steps. This custom metric can be used with other fundamental metrics.</p><p>It is also important to note that these evaluation metrics are similar to functional tests in traditional software development: they evaluate whether the system behaves correctly for a given input. However, comprehensive evaluation should also include non-functional aspects such as <strong>performance</strong> and <strong>security</strong>. For example, latency can be tracked with metrics such as time to first token, and security can be evaluated with custom metrics such as PII leakage or tests that check how the model responds when harmful or sensitive content appears in retrieved documents or in the query.</p><p><strong>Making a Final Decision (with Human Labeling)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*uwWyJFkDB7773ZwcVtb-gA.png" /><figcaption>Hierarchical decision process of RAG Evaluation metrics</figcaption></figure><p>We use multiple metrics during evaluation, but the key question remains: how do we make a final decision?</p><p>In our case, we follow a hierarchical decision process.</p><p>First, we check document accuracy. If this fails, the test case is immediately marked as failed.</p><p>If it passes, we continue with contextual relevancy and contextual recall to verify whether the correct context (or chunk) has been retrieved. If these metrics fail, the test case is also marked as failed.</p><p>If retrieval-related metrics pass, we proceed with answer relevancy and faithfulness to evaluate the quality of the generated response.</p><p>If all of these metrics pass, the test case is labeled as successful.</p><p>While this hierarchical approach provides a structured way to make decisions, it is not always sufficient on its own.</p><p>In practice, some cases still require <strong>human labeling</strong>, particularly when metrics produce conflicting results or when the evaluation outcome is unclear.</p><p>Rather than replacing automated evaluation, human labeling acts as a final verification layer.</p><p><strong>Conclusion</strong></p><p>RAG evaluation remains an evolving and inherently complex problem, and it cannot be reduced to a single metric or a fixed evaluation setup. Effective evaluation requires <strong>understanding system-specific failure modes and customizing the appropriate metrics to capture them</strong>. Foundational, RAG Triad metrics such as Faithfulness, Contextual Relevancy, and Answer Relevancy help identify common issues, but they are not sufficient to reflect real-world system behavior.</p><p>LLM-as-a-judge methods play an important role in RAG evaluation. However, consistency and reliability are still challenges.</p><p>At the moment, human evaluation is necessary. But it is costly and hard to scale.</p><p>This creates a need for more automated evaluation pipelines. In cases where large models cannot be used due to cost, privacy, or compliance constraints, smaller models can be fine-tuned to align with human evaluation. This can reduce reliance on human evaluators and enable a more scalable evaluation process.</p><p>In addition, evaluation datasets must evolve beyond static benchmarks. Instead of relying on fixed test sets, teams should continuously update evaluation data by logging real user queries, capturing failure cases, and curating edge scenarios. This ensures that evaluation remains aligned with real-world usage and adapts as systems and user behavior change.</p><p>As a final note, RAG evaluation should be treated as a continuous and iterative process rather than a one-time benchmark. Integrating evaluation into CI/CD pipelines enables continuous validation, early detection of regressions, and more reliable system performance over time.</p><p><strong>References</strong></p><p>RAG Triad, <a href="https://www.trulens.org/getting_started/core_concepts/rag_triad">https://www.trulens.org/getting_started/core_concepts/rag_triad</a></p><p>RAGAS: Automated Evaluation of Retrieval-Augmented Generation, <a href="https://arxiv.org/abs/2309.15217">https://arxiv.org/abs/2309.15217</a></p><p>Ragas Documentation, <a href="https://docs.ragas.io/en/stable/">https://docs.ragas.io/en/stable/</a></p><p>DeepEval Documentation, <a href="https://deepeval.com/docs/getting-started-rag">https://deepeval.com/docs/getting-started-rag</a></p><p>Deepeval vs Ragas, <a href="https://deepeval.com/blog/deepeval-vs-ragas">https://deepeval.com/blog/deepeval-vs-ragas</a></p><p>DeepEval GitHub Repository, <a href="https://github.com/confident-ai/deepeval">https://github.com/confident-ai/deepeval</a></p><p>Benchmarking Large Language Models in Retrieval-Augmented Generation, <a href="https://arxiv.org/abs/2309.01431">https://arxiv.org/abs/2309.01431</a></p><p>RAGChecker: A Fine-grained Framework for Diagnosing Retrieval-Augmented Generation, <a href="https://arxiv.org/pdf/2408.08067">arxiv.org/pdf/2408.08067</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8f35a4cd93b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/yapi-kredi-teknoloji/rag-evaluation-challenges-and-practical-insights-e8f35a4cd93b">RAG Evaluation Challenges and Practical Insights</a> was originally published in <a href="https://medium.com/yapi-kredi-teknoloji">Yapı Kredi Teknoloji</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finetuning Sentence Embedding Models to Enhance Retrieval in RAG]]></title>
            <link>https://medium.com/yapi-kredi-teknoloji/finetuning-sentence-embedding-models-to-enhance-retrieval-in-rag-5e5cd9f127c2?source=rss-3bffaee71ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e5cd9f127c2</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <category><![CDATA[sentence-transformers]]></category>
            <category><![CDATA[model-finetuning]]></category>
            <category><![CDATA[sentence-embedding]]></category>
            <dc:creator><![CDATA[Yudum Paçin]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 08:01:56 GMT</pubDate>
            <atom:updated>2025-02-25T08:01:56.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99hWaitOhWUknSriLLbJ3A.jpeg" /></figure><p>Sentence embeddings serve as the backbone of semantic search in the retrieval component of Retrieval-Augmented Generation (RAG). They convert document chunks into token embeddings and then aggregate these into a single sentence-level embedding using strategies like mean pooling (averaging all token embeddings), max pooling (selecting the maximum value from each dimension), or directly using the [CLS] token representation from transformer models. The quality of these embeddings—how well they represent the semantic meaning of sentences—directly influences retrieval performance and, consequently, the overall accuracy of the RAG system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4SGWuJk-zIfSs1nP82mtg.png" /><figcaption>The process of transforming a sentence into a vector using a sentence transformer model.</figcaption></figure><p>In this blog, I will show how to finetune a sentence embedding model on a Turkish domain-specific dataset to improve retrieval accuracy. The fine-tuning process uses Multiple Negatives Ranking Loss combined with Matryoshka Loss, following the training scripts referenced in [1].</p><p><strong>1-</strong> <strong>Select a Base Model</strong></p><p>In my use case, all the documents in knowledge base are Turkish, so I definitely need a base model that has been trained on Turkish data. Fortunately, Hugging Face offers numerous open-source sentence transformer models that support Turkish.</p><p>The ‘best’ model can vary depending on the knowledge base, so it’s important to experiment and evaluate models on your own documents. Start by creating a test dataset of query-chunk pairs. You can then use the <a href="https://sbert.net/docs/package_reference/sentence_transformer/evaluation.html">InformationRetrievalEvaluator</a> to assess the performance of the base model. Once you’ve selected a suitable base model, you can move on to finetuning the sentence embedding model. Finetuning involves four key components: <strong>the dataset, loss function, training arguments, </strong>and<strong> evaluator.</strong></p><p><strong>2-</strong> <strong>Dataset</strong></p><p>To prepare the training data, you need a set of query-chunk pairs, where the queries are questions, and the chunks are segments of documents. These chunks are used to compare similarities with query embeddings in RAG systems. Fortunately, there are some open-source Turkish datasets available for this purpose, such as:</p><p>· <a href="https://github.com/boun-tabi/squad-tr">SQuAD-Tr</a></p><p>· <a href="http://metin/WikiRAG-TR%20%C2%B7%20Datasets%20at%20Hugging%20Face">WikiRAG-Tr</a></p><p>For domain-specific applications, it is essential to include relevant domain-specific jargon, synonyms, and acronyms in the dataset. For instance, in Turkish financial contexts, synonyms like ‘ortak-müşterek’ or ‘yatırım fonu-portföy’ should be represented in the training data. In the case of open source data, the dataset can be filtered to focus on Turkish financial terms.</p><p>The most important aspect of the training data is to incorporate your own documents. If you already have a question-answer dataset, such as FAQs, it is a good idea to add them to the training dataset. Additionally, you can enhance your dataset by generating synthetic questions from your documents using an LLM. Below is an example of a question-generation prompt template. You can customize the prompt to suit your specific needs. For instance, you could change the role to a teacher or researcher, or include real-world questions and answers to create a few-shot prompting setup.</p><pre>Sadece metin içeriğine göre sorulabilecek 3 soruyu array içerisinde string olarak yaz.<br>Örnek: [\&quot;soru1\&quot;, \&quot;soru2\&quot;, \&quot;soru3\&quot;]<br>Soruları konu hakkında bilgi öğrenmek isteyen bir banka şubesi çalışanıymış gibi sor.<br>Metin: {}</pre><p>Another alternative to using LLMs in this phase is filtering existing Q&amp;A pairs by evaluating whether the query chunks are relevant to the questions. Relevant pairs are retained, ensuring the dataset remains accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUN8MWvUTdzZWdJkRGQa6w.png" /><figcaption>Synthetic data generation with LLM</figcaption></figure><p>After gathering your dataset, ensure it includes columns for id, anchor (query) and positive (chunk). Also split the dataset into training, validation (dev), and test sets for training, evaluation, and testing purposes. An example code snippet is provided below.</p><pre>from datasets import load_dataset, Dataset<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br><br># Load the dataset from https://huggingface.co/datasets/Metin/WikiRAG-TR [3]<br>dataset = load_dataset(&quot;Metin/WikiRAG-TR&quot;)[&quot;train&quot;] #load all data<br><br># Make sure you have &quot;anchor&quot; (question) and &quot;positive&quot; (context) fields only.<br># Renaming is optional<br>dataset = dataset.map(lambda x: {&quot;anchor&quot;: x[&quot;question&quot;], &quot;positive&quot;: x[&quot;context&quot;]}, remove_columns=dataset.column_names)<br><br># Convert the Dataset to DataFrame for splitting<br>df = pd.DataFrame(dataset)  <br><br># Add an &#39;id&#39; column based on the index<br>df[&#39;id&#39;] = df.index<br><br># Split into train (80%), validation (10%), and test (10%) sets<br>train_df, temp_df = train_test_split(df, test_size=0.2, random_state=42)  <br>dev_df, test_df = train_test_split(temp_df, test_size=0.5, random_state=42)  <br><br># Convert to Datasets<br>train_dataset = Dataset.from_pandas(train_df.reset_index(drop=True))<br>dev_dataset = Dataset.from_pandas(dev_df.reset_index(drop=True))<br>test_dataset = Dataset.from_pandas(test_df.reset_index(drop=True))</pre><p><strong>3-</strong> <strong>Loss</strong></p><p>The loss function in machine learning models is defined as the difference between actual and predicted values, and the objective is to optimize the model’s parameters to minimize this loss. To compute the loss for embedding models, a similarity metric is required to compare vector representations. Cosine similarity is commonly used for this purpose, as it measures how similar two vectors are by calculating the cosine of the angle between them. When two embedding are aligned (cosine angle close to 0), their similarity is cos(0) = 1. Ideally, the cosine similarity for a query-answer pair (positive pair) should be close to 1, while the similarity with other chunks (negative pairs) should be close to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPnxHjR0axtUpBRtuCCJkA.png" /><figcaption>A High-Level Representation of Multiple Negatives Ranking Loss Calculation</figcaption></figure><p>The finetuning process uses the Multiple Negatives Ranking Loss as the loss function. You can explore other loss functions <a href="https://sbert.net/docs/sentence_transformer/loss_overview.html#custom-loss-functions">here</a>. To apply this loss, all you need are queries and their corresponding positive (correct) answers. For details on setting up this dataset, refer to <strong>Part 2: Dataset</strong>.</p><p>In Multiple Negative Ranking Loss, each query in a batch is paired with one positive chunk, while all other chunks in the batch are treated as negatives. For a batch of n query-chunk pairs, this results in one positive and n−1 negatives per query. The loss works by first calculating softmax-normalized similarity scores, which are scaled by a predefined factor. Then, it applies cross-entropy to minimize the negative log-likelihood. This maximizes the similarity for positive pairs and minimizes the similarity for negatives.</p><p>Multiple Negatives Ranking Loss for a query in a single batch can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*iw3758gyYdHKg-ObMh3rFQ.png" /></figure><p>The full implementation of the Multiple Negatives Ranking Loss is here: <a href="https://github.com/UKPLab/sentence-transformers/blob/master/sentence_transformers/losses/MultipleNegativesRankingLoss.py">https://github.com/UKPLab/sentence-transformers/blob/master/sentence_transformers/losses/MultipleNegativesRankingLoss.py</a></p><p><strong>Matroushka Representation Learning</strong></p><p>Traditional embedding models create fixed-size vectors to represent text. Matryoshka Representation Learning (MRL), on the other hand, enables the use of variable-sized vectors. For instance, from a 768-dimensional embedding, smaller embeddings of 512, 256, 128, or 64 dimensions can be derived, making the representation adaptable to different tasks and resource constraints.</p><p>MRL achieves this by modifying the loss function to optimize multiple dimensional ranges instead of a single fixed dimension (e.g., 768). The overall loss is computed as the sum of individual losses for each dimensional subset, enabling the model to generate effective representations across various sizes.</p><p>With MRL, large embedding models can be used in truncated dimensions, making them suitable for resource-limited environments. Another use case is using smaller embeddings for an initial shortlist, followed by re-ranking with full-sized embeddings [2]. This approach helps filter candidates quickly while refining results with higher-dimensional embeddings.</p><p>In my use case, combining MatryoshkaLoss with Multiple Negative Ranking Loss has resulted in better results compared to using Multiple Negative Ranking Loss alone. Thanks to the SentenceTransformers, implementing <strong>Matryoshka Representation Learning</strong> with <strong>Multiple Negative Ranking Loss</strong> is easy, you can use MatryoshkaLoss as below.</p><pre>from sentence_transformers.losses import MatryoshkaLoss, MultipleNegativesRankingLoss<br>from sentence_transformers import SentenceTransformer<br><br>model = SentenceTransformer(&quot;intfloat/multilingual-e5-base &quot;)<br><br>inner_train_loss = MultipleNegativesRankingLoss(model)<br><br>matryoshka_dims = [768, 512, 256, 128, 64]<br><br>train_loss = MatryoshkaLoss(model, inner_train_loss, matryoshka_dims = matryoshka_dims)</pre><p><strong>Evaluator</strong></p><p>During finetuning, it is essential to use an evaluator to measure performance improvements. In the case of RAG, the InformationRetrievalEvaluator is well-suited for this task. This evaluator works by taking a set of queries and a large corpus and retrieving the top-k most similar documents for each query. It then measures performance using metrics such as Accuracy, Mean Reciprocal Rank (MRR), Recall, Precision and Normalized Discounted Cumulative Gain (NDCG) to evaluate retrieval effectiveness.</p><pre>from sentence_transformers.util import cos_sim<br>from sentence_transformers.evaluation import InformationRetrievalEvaluator, SequentialEvaluator<br><br># Create queries and corpus dictionaries from the dev set <br><br>queries_dev = dict(zip(dev_dataset[&quot;id&quot;], dev_dataset[&quot;anchor&quot;])) <br>corpus_dev = dict(zip(dev_dataset[&quot;id&quot;], dev_dataset[&quot;positive&quot;]))<br><br>evaluators = []<br><br>for dim in matryoshka_dims:<br>    evaluators.append(<br>        InformationRetrievalEvaluator (<br>            queries = queries_dev,<br>            corpus = corpus_dev,<br>            score_functions= {&quot;cosine&quot;: cos_sim},<br>            relevant_docs = {q_id: [q_id] for q_id in queries_dev},<br>            name=f&quot;dev-{dim}&quot;,<br>            truncate_dim=dim,<br><br>        )<br>    )<br>dev_evaluator = SequentialEvaluator(evaluators)</pre><p><strong>Training Arguments</strong></p><p>The final step is to configure the SentenceTransformerTrainingArguments parameters. Below, I provide training parameters, but you should adjust them based on your resource limitations, dataset size, and specific training requirements. Setting per_device_train_batch_size=4 and gradient_accumulation_steps=2 results in a batch size of 8, where each batch processes 8 question-chunk pairs to compute the MultipleNegativesRankingLoss. If the GPU/TPU hardware allows, increasing the batch size can improve results.</p><p>For further details on available parameters, you can check the <a href="https://sbert.net/docs/package_reference/sentence_transformer/training_args.html">sentence-transformers documentation</a>.</p><pre>from sentence_transformers import SentenceTransformerTrainer, SentenceTransformerTrainingArguments<br><br>args = SentenceTransformerTrainingArguments(<br>    output_dir=&quot;./output&quot;,<br>    num_train_epochs=3,<br>    per_device_train_batch_size=4,<br>    gradient_accumulation_steps=2,<br>    per_device_eval_batch_size=2,<br>    learning_rate=2e-5,<br>    eval_strategy=&quot;steps&quot;,<br>    eval_steps=200,<br>    save_total_limit=3,<br>    save_strategy=&quot;steps&quot;,<br>    save_steps=200,<br>    load_best_model_at_end=True,<br>    logging_steps=200,<br>    metric_for_best_model = &#39;eval_dev-768_cosine_accuracy@3&#39;<br>)<br><br>trainer = SentenceTransformerTrainer(<br>    model=model,<br>    args=args,<br>    train_dataset=train_dataset.select_columns([&quot;anchor&quot;,&quot;positive&quot;]),<br>    loss=train_loss,<br>    evaluator= dev_evaluator,<br>   )<br>trainer.train()</pre><p>Lastly<strong>,</strong> test the model using the test set. You can also run this code before the finetuning process to evaluate the performance of the base model on the same test dataset.</p><pre># Create queries and corpus dictionaries from the test set <br><br>queries_test = dict(zip(test_dataset[&quot;id&quot;], test_dataset[&quot;anchor&quot;])) <br>corpus_test = dict(zip(test_dataset[&quot;id&quot;], test_dataset[&quot;positive&quot;]))<br><br>evaluators = []<br><br>for dim in matryoshka_dims:<br>    evaluators.append(<br>        InformationRetrievalEvaluator (<br>            queries = queries_test,<br>            corpus = corpus_test,<br>            score_functions= {&quot;cosine&quot;: cos_sim},<br>            relevant_docs = {q_id: [q_id] for q_id in queries_test}, <br>            name=f&quot;test-{dim}&quot;,<br>            truncate_dim=dim,<br><br>        )<br>    )<br>test_evaluator = SequentialEvaluator(evaluators)<br>test_evaluator(model)</pre><p>Finally, I present the test results before and after finetuning for this example. As shown, there is a reasonable improvement in accuracy@3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ErLxfmaTvcypaQOSIUiW_g.png" /></figure><p>Finetuning an embedding model for RAG is an iterative process. If your documents are updated and similarity scores decrease significantly, you will need to repeat the finetuning process. Additionally, after finetuning, ensure that you index your documents in the vector store using the finetuned model to maintain optimal retrieval performance.</p><p><strong>References</strong></p><p>[1] Training — Matryoshka: Code Examples. Sentence Transformers, <a href="https://sbert.net/examples/training/matryoshka/README.html#code-examples">https://sbert.net/examples/training/matryoshka/README.html#code-examples</a>.</p><p>[2] Kusupati, A., Bhatt, G., Rege, A., Wallingford, M., Sinha, A., Ramanujan, V., Howard-Snyder, W., Chen, K., Kakade, S., Jain, P., &amp; Farhadi, A. (2024). Matryoshka Representation Learning. arXiv. <a href="https://arxiv.org/abs/2205.13147">https://arxiv.org/abs/2205.13147</a></p><p>[3] WikiRAG-TR [Dataset]. Hugging Face. <a href="https://huggingface.co/datasets/Metin/WikiRAG-TR">https://huggingface.co/datasets/Metin/WikiRAG-TR</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e5cd9f127c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/yapi-kredi-teknoloji/finetuning-sentence-embedding-models-to-enhance-retrieval-in-rag-5e5cd9f127c2">Finetuning Sentence Embedding Models to Enhance Retrieval in RAG</a> was originally published in <a href="https://medium.com/yapi-kredi-teknoloji">Yapı Kredi Teknoloji</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Improve Retrieval Performance in RAG]]></title>
            <link>https://medium.com/yapi-kredi-teknoloji/how-to-improve-retrieval-performance-in-rag-e63ea641aa0c?source=rss-3bffaee71ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e63ea641aa0c</guid>
            <category><![CDATA[advanced-retrieval]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[retrieval]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <dc:creator><![CDATA[Yudum Paçin]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 08:02:27 GMT</pubDate>
            <atom:updated>2025-01-28T08:02:27.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2YDlO4TP7M1CxvXjHKW1Q.jpeg" /></figure><p>Large Language Models (LLMs) have become essential revolutionizing how we process information, automate workflows, and solve complex problems. However, they may still produce inaccurate responses, especially when dealing with domain-specific or up-to-date knowledge. Retrieval-Augmented Generation (RAG) addresses this by adding relevant context to the LLM’s prompt. The main challenge is efficiently retrieving the most relevant information from large knowledge bases. In this blog post, I will outline strategies to improve retrieval accuracy in RAG application with Turkish Banking Documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ppQZ_QpX_V_RqXuaa9ggg.png" /><figcaption>Retrieval in Naive RAG</figcaption></figure><p>In the naive RAG method, retrieval typically involves searching the top similar documents of a query using cosine similarity within an embedding space. This search is conducted through a vector store created by indexing a knowledge base of various documents. However, working with a large database of Turkish banking documents in diverse formats — such as pdf, docs, xlsx, csv — this naive approach often fails.</p><p>So, how can we improve retrieval success? First, we need to define what success means. Without a clear definition, how can we ensure we are improving? Fortunately, there are existing metrics from information retrieval area. These metrics have been used for decades in search engines and recommendation systems before RAG.</p><p>To begin exploring metrics, you should establish a ground truth dataset comprising queries and document chunks that contain the answers to these queries. Building such a dataset can be challenging, especially if you only have documents and lack human involvement in the process. In such cases, you can leverage LLMs to generate synthetic questions based on given document chunks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*MW819EFaTeaGNabcegZPEA.png" /><figcaption>Source: <a href="https://x.com/helloiamleonie/status/1838035568577347914">https://x.com/helloiamleonie/status/1838035568577347914</a></figcaption></figure><p>Now, let’s examine some commonly used metrics:</p><ul><li><strong>Accuracy@k</strong> measures whether a relevant item is found within the top k results for each query. It is a binary evaluation (hit or miss) calculated per query, and the average accuracy across all queries is taken as the final score.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*spp8-iO2rRLnGttYJhZU8g.png" /></figure><p>· <strong>Precision@k</strong> evaluates the fraction of relevant items among the top k results for a query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*T1KR2cqvUuBPPYGgOCXRGw.png" /></figure><p>· <strong>Recall@k</strong> measures how many of the total relevant items are returned within the top k results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*Syx-D3WqldrMi5zF0laAaw.png" /></figure><p>Precision and recall is calculated per query, and the average is taken across the entire evaluation set.</p><p>· <strong>Mean Reciprocal Rank (MRR)</strong> Mean Reciprocal Rank (MRR) measures the position of the first relevant item in the results. It is calculated as the average of the reciprocal ranks across all queries. If the first relevant document is ranked first, the reciprocal rank is 1. If it appears second, the reciprocal rank becomes 1/2, if it is third, 1/3, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*txxfzaCdIH1NbpW1ZoYy1Q.png" /></figure><p>· <strong>Discounted Cumulative Gain (DCG)</strong> measures the total relevance of the returned documents. It sums the relevance scores of all retrieved documents for a query while applying a logarithmic discount factor to reduce the weight of lower-ranked items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*vwBbw1MqYsZNGg02S8Yb8A.png" /></figure><p>· <strong>Normalized Discounted Cumulative Gain (NDCG)</strong> is a normalized version of DCG. To calculate NDCG@k, DCG@k is divided by the Ideal DCG (IDCG), which represents the highest possible DCG score if all items were perfectly ranked by relevance. NDCG values range from 0 to 1, with higher values indicating better alignment of rankings with relevance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*XUf9JqjDJBw-Zwlx3JGzbw.png" /></figure><p>You can use libraries like <a href="https://sbert.net/docs/package_reference/sentence_transformer/evaluation.html">InformationRetrievalEvaluator </a>, <a href="https://amenra.github.io/ranx/">ranx </a>to calculate these metrics.</p><p>Understanding these metrics is important to improve the performance of RAG. For example, if accuracy@10 is 0.7 and MRR is 0.3, it means that we correctly retrieve relevant results for 7 out of 10 queries, but the top relevant item is often ranked around the 3rd position on average. According to a research study [1], the retriever’s highest-scoring documents that are not directly relevant to the query (e.g., do not contain the answer) can negatively impact the effectiveness of the LLM. Thus, it is not only important to achieve a high hit rate (whether the correct document is found), but also to ensure that the correct document appears early in the ranked list, near to the query. Both factors significantly affect RAG performance.</p><p>Accuracy@k and MRR@k metrics are used to measure retrieval success in this use case. If you have multiple correct chunks and their correct order in your test dataset, you can also consider metrics like precision, recall, and NDCG (Normalized Discounted Cumulative Gain) to evaluate retrieval performance.</p><p><strong>Data Quality</strong></p><p>It’s a bit of a cliché, but it is worth repeating: “Garbage in, garbage out.” Regardless of the type of data you’re working with, ensuring the data is as clean as possible is critical for achieving success. This step can be one of the most challenging in the pipeline, often requiring human involvement. While Document loaders of existing RAG frameworks like <a href="https://python.langchain.com/v0.1/docs/modules/data_connection/document_loaders/">langchain </a>can help with parsing documents, specialized cases may require additional libraries, such as <a href="https://unstructured.io/">unstructured </a>, <a href="https://github.com/nlmatics/llmsherpa">llmsherpa</a>. After parsing, you can remove noise (e.g., page numbers or special characters) that could disrupt retrieval. Apply the same preprocessing steps to queries to ensure consistency.</p><p>While discussing noise, I want to highlight two interesting findings about its role in RAG. In [1], it is suggested that “random noisy documents can actually help increase the accuracy of RAG systems when correctly positioned within a prompt.” Additionally, another study [2] states that grammatically incorrect or nonsensical sentence fragments can enhance RAG performance. Perhaps, instead of eliminating all noise, we should consider being more open to it — at least the useful ones in generation phase of RAG systems.</p><p><strong>Hybrid Search</strong></p><p>In general, RAG applications rely on sentence embedding models to represent document chunks and queries as vectors. While embedding can generalize to unseen queries, performance may decline for queries that differ significantly from the training set, particularly in domain-specific or low-resource language use cases. Finetuning embedding is an effective way to improve retrieval, which I will mention in following sections again, but this process may be time-consuming. Keyword search can complement embedding-based retrieval to enhance results, especially for exact matches or rare domain-specific terms. Additionally, its language-independent performance makes it particularly useful for my use case: Turkish banking documents.</p><p>Most common keyword search technique is BM25 (Best Match 25 or Okapi 25). In a high level definition, BM25 ranks documents by evaluating the relevance of terms in a query using a combination of term frequency (how often a term appears in a document) and inverse document frequency (how unique the term is across the corpus). Vector databases may modify the implementation of BM25 to optimize inference performance. You can use <a href="https://python.langchain.com/docs/how_to/ensemble_retriever/">LangChain’s BM25 retriever</a> with in-memory vector stores like FAISS. However, as the size of the document corpus grows, you may need the support of a vector database to store BM25 sparse vectors efficiently. To find vector databases that support BM25, refer to the <a href="https://superlinked.com/vector-db-comparison">Vector DB Comparison</a> tool and filter by BM25 compatibility.</p><p>Hybrid search is often implemented using Reciprocal Rank Fusion (RRF) by blending ranking orders from two retrieval methods, keyword search and embedding search. Interestingly, in our experiments, hybrid search tends to show smaller improvements in Mean Reciprocal Rank (MRR) compared to accuracy across all k values.</p><p><strong>Cross Encoder Rerankers</strong></p><p>Cross-encoder rerankers, significantly enhance retrieval performance in RAG systems by jointly evaluating query-document pairs for precise ranking. Cross-encoders are slower than bi-encoders because they compute relevance scores for each query-document pair sequentially, requiring the model to process both inputs together. Despite their computational overhead, they are essential.</p><p>Multilingual cross-encoders supporting the Turkish language include several options, and in our use case, <a href="https://huggingface.co/BAAI/bge-reranker-v2-m3"><strong>bge-reranker-v2-m3</strong></a> proved to be the most successful. However, new open-source models or updated versions emerge so often. Regularly checking the ranking section of the <a href="https://huggingface.co/spaces/mteb/leaderboard"><strong>MTEB leaderboard</strong></a> and experimenting with different models is crucial.</p><p><strong>Small to Big Retrieval (Parent Document Retriever)</strong></p><p>The Small-to-Big Retrieval method is a common approach in RAG systems that balances the strengths of retrieval and generation. This approach works by first retrieving relevant small chunks (child chunks) and then referencing the larger chunks (parent chunks) encompassing the child chunk to the LLM. To implement this method with langchain, you can check <a href="https://python.langchain.com/docs/how_to/parent_document_retriever/">parent document retriever</a>.</p><p><strong>Tuning the RAG Parameters</strong></p><p><strong>Chunk Size</strong></p><p>Chunk size is crucial in RAG systems, as it impacts both retrieval and generation performance. To optimize chunk size, experiment with sizes ranging from 100 to 500 tokens, adjusting the chunk overlap parameter to maintain context continuity. Consider using TokenTextSplitter instead of RecursiveCharacterSplitter to align with the LLM’s context size, ensuring more efficient and accurate processing.</p><p><strong>Optimize the Indexing parameters</strong></p><p>Most vector databases use HNSW (Hierarchical Navigable Small World) method to find similar items efficiently. HNSW is structured as a multi-layered graph where vectors (data points) are nodes, and these nodes are connected based on how similar they are. The top layer has very few connections (sparse), while each layer below it adds more connections, making the bottom layer the densest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*mFIBfGMMU0fhrBrW69BG8A.png" /><figcaption>Representation of HNSW generated with DALL-E</figcaption></figure><p>To control how this system works, there are two important settings:</p><p>1. <strong>m (Maximum Connections per Node)</strong>:<br> This determines how many connections each node can have. Increasing m makes the graph more detailed, improving the accuracy of the search by bringing results closer to a perfect match. However, this also increases memory usage and slows down searches because the graph becomes larger and more complex.</p><p>2. <strong>ef (Points Checked at Each Layer)</strong>:<br> This decides how many points the system examines at each layer when searching. At each level, the system keeps the ef closest points and moves to the next layer. This process continues until the final layer, where it picks the best matches. A higher ef value improves accuracy but makes searches slower because it has to process more points.</p><p>For example, in Qdrant, the default settings are m=16 and ef=100. Increasing these values probably give better search results but also slows the indexing and retrieval process down and uses more memory. It’s important to find the right balance for your needs: higher values are great for precision but come with trade-offs in speed and resource usage [3].</p><p><strong>Finetune Embedding Model (Bi-encoder) and Cross-Encoder Reranker Model</strong></p><p>The embedding model is one of the most critical components in a RAG system. It functions as an encoder, converting text into vectors that represent semantic meaning. Different architectures are used for encoders, such as dual-encoders, bi-encoders, and cross-encoders. For the retrieval part, the most common approach is bi-encoders, which use the same model to generate vectors for both queries and documents. Some embedding models, like e5, require instruction prompts differentiating query and passage to improve performance. In dual-encoder setups, questions and documents are encoded with different retrievers.</p><p>Finetuning bi-encoder models is an excellent way to boost retrieval performance, especially for non-English, domain-specific data like Turkish banking documents. Finetuning aligns the embedding model with the specific dataset, but it requires training data which can be time-intensive to create. I plan to share recipe notebooks for finetuning bi-encoder models in future posts.</p><p>Finetuning cross-encoders, also essential for improving retrieval performance especially for domain-specific or non-English languages.</p><p>Llama-Index finetuning notebooks provide training recipes with synthetic data generation for a given document, making them a great starting point if you have not any training data. I am adding the finetuning notebook links below for both embedding and cross encoders. However, I recommend inspecting the source codes from llama-index github page and creating your own data scripts by experimenting with training hyperparameters (e.g., batch size, epochs), loss functions, and evaluators using the Sentence Transformers library, as in their approach.</p><p>Llama-index embedding finetuning:</p><p><a href="https://docs.llamaindex.ai/en/stable/examples/finetuning/embeddings/finetune_embedding/">https://docs.llamaindex.ai/en/stable/examples/finetuning/embeddings/finetune_embedding/</a></p><p>Llama-index cross-encoder finetuning:</p><p><a href="https://docs.llamaindex.ai/en/stable/examples/finetuning/cross_encoder_finetuning/cross_encoder_finetuning/">https://docs.llamaindex.ai/en/stable/examples/finetuning/cross_encoder_finetuning/cross_encoder_finetuning/</a></p><p><strong>Benefiting from the Metadata</strong></p><p>When a user searches for “What are the most recent mortgage interest rates?” it can be nearly impossible to retrieve the correct document if the document’s date is not included in the context. Often, the date is stored as metadata, separate from the main text. By leveraging metadata fields like dates, we can significantly enhance retrieval accuracy for time-sensitive queries.</p><p>In addition to dates, other metadata fields such as file names, titles can provide valuable compact summaries of the content. Including this metadata as part of the chunks during retrieval ensures that this micro-level information contributes to the ranking process. For example, a file name or title might directly hint at the document’s relevance to the query, increasing the likelihood of retrieving the correct document. By enriching chunks with relevant metadata, the retrieval model gains additional context, leading to improved performance and more accurate results.</p><p><strong>A Little Bit of Help from LLM</strong></p><p>Using LLMs during the retrieval or ranking phase sounds promising and easy. Prompts like “Give me the most relevant context” or “Rank the chunks from most similar to least” can be used directly. However, relying solely on LLMs for such tasks can be overkill, akin to using a kitchen robot to slice an orange. There are two main challenges: high computational cost and no guarantee of consistent success. That said, using LLMs for smaller, focused tasks for retrieval is more practical and promising. Below are methods where a little assistance from LLMs can be effective. However, the success of these methods heavily depends on the capabilities of the LLM. In my case, using finetuned meta-llama/Llama-3.1–8B-Instruct model and similar sized LLMs didn’t significantly improve retrieval scores. However, I believe domain-specific or Turkish language-optimized LLMs could yield better results.</p><p><strong>Chunk Summarization</strong></p><p>Chunks should be compact and include the essential context for retrieval. As discussed in the small to big retrieval approach, smaller chunks generally work better for retrieval. However, if a chunk lacks sufficient context, it can become useless. Chunk summarization offers an alternative by compressing the information in a chunk, but it requires a capable LLM. This approach risks introducing irrelevant or fabricated information, as LLMs can sometimes hallucinate. In our experiments, using the original chunks yielded better results than LLM-generated summaries.</p><p><strong>Query Expansion/Rewriting</strong></p><p>When users search, their queries may not always be precise — they might include synonyms, affiliations, or ambiguous terms. Query expansion or rewriting with LLMs can improve retrieval by broadening the search scope or clarifying the query. However, like chunk summarization, this method requires additional LLM calls and works best with finetuned or larger models. In my case, expanding the number of retrieved candidates (larger k) yielded moderate success, but results were inconsistent across queries.</p><p><strong>Conclusion</strong></p><p>I started this blog by giving a naive retrieval diagram. As we went along, I introduced more advanced techniques that I used. Now, I’ve updated the diagram to highlight the most effective methods found, that truly boost retrieval scores. These additions may give you an idea to improving your own RAG systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9yxp8B_ikDc82uxM5WvMA.png" /><figcaption>RAG with Advanced<strong> </strong>Retrieval Methods</figcaption></figure><p>I’ve shared the results, highlighting the methods that worked well, don’t contribute, negatively impact with smiley faces below :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*7eW4RoKcHRDMBcR8trxbHQ.png" /></figure><p><strong>Is That All?</strong></p><p>RAG is a rapidly evolving field, with new retrieval methods emerging almost every week. While this blog post has covered some widely used approaches, several promising methods are yet to be explored. I plan to experiment with techniques like Late Chunking, ColBERT, Contextual Document Embedding in the future. Each of these methods offers unique strategies to improve retrieval performance. Stay tuned for updates as I dive into these exciting methodologies in future posts!</p><p><strong>References</strong></p><p>[1] Cuconasu, F., Trappolini, G., Siciliano, F., Filice, S., Campagnano, C., Maarek, Y., Tonellotto, N., &amp; Silvestri, F. (2024). The Power of Noise: Redefining Retrieval for RAG Systems. arXiv preprint arXiv:2401.14887.</p><p>[2] Wu, J., Che, F., Zhang, C., Tao, J., Zhang, S., &amp; Shao, P. (2024). Pandora’s Box or Aladdin’s Lamp: A Comprehensive Analysis Revealing the Role of RAG Noise in Large Language Models. arXiv preprint arXiv:2408.13533.</p><p>[3] <strong>Optimizing HNSW Search — Retrieval Optimization: From Tokenization to Vector Quantization. </strong><em>DeepLearning.AI.</em> [Video]. Retrieved from <a href="https://learn.deeplearning.ai/courses/retrieval-optimization-from-tokenization-to-vector-quantization/lesson/6/optimizing-hnsw-search">https://learn.deeplearning.ai/courses/retrieval-optimization-from-tokenization-to-vector-quantization/lesson/6/optimizing-hnsw-search</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e63ea641aa0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/yapi-kredi-teknoloji/how-to-improve-retrieval-performance-in-rag-e63ea641aa0c">How to Improve Retrieval Performance in RAG</a> was originally published in <a href="https://medium.com/yapi-kredi-teknoloji">Yapı Kredi Teknoloji</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>